关于java:Note剑指offer50

原题

在字符串 s 中找出第一个只呈现一次的字符。如果没有,返回一个单空格。 s 只蕴含小写字母。

思路

  • 第一次遍历应用字典贮存
  • 第二次遍历寻找第一个次数为1的字符,若没找到返回’ ‘

代码

package offer;
import java.util.Scanner;
public class offer50 {
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        String s=sc.next();
        System.out.println(new Solution().firstUniqChar(s));
    }
}
class Solution {
    public char firstUniqChar(String s) {
        int [] c=new int [26];
        char t;
        for(int i=0;i<s.length();i++){
            t=s.charAt(i);
            c[t-'a']++;
        }
        for(int i=0;i<s.length();i++){
            t=s.charAt(i);
            if(c[t-'a']==1){ return t; }
        }
        return ' ';
    }
}

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理