原题
在字符串 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 ' ';
}
}
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论