自己写的代码,很冗余,但是竟然效率还挺高
public char firstUniqChar(String s) {
if ("".equals(s)) return 0;
char[] arr = s.toCharArray();
int[] res = new int[128];
for (char c : arr) {
res[c]++;
}
ArrayList<Character> list = new ArrayList<>();
for (int i = 0; i < 128; i++) {
if (res[i] == 1){
list.add((char) i);
}
}
if (list.size() == 0) return ' ';
int min = Integer.MAX_VALUE;
for (int i = 0; i < list.size(); i++) {
min = Math.min(min,s.indexOf(list.get(i)));
}
return arr[min];
}
评论区:字符串 indexOf() 写法
代码来源:
https://leetcode-cn.com/problems/di-yi-ge-zhi-chu-xian-yi-ci-de-zi-fu-lcof/comments/
public char firstUniqChar(String s) {
for (int i = 0; i < s.length(); i++) {
char ch=s.charAt(i);
//首次出现的位置是当前位置,且后面没有再出现这个字符
if(s.indexOf(ch)==i && s.indexOf(ch,i+1)==-1)
return s.charAt(i);
}
return ' ';
}
简洁写法:数组哈希
代码来源:
https://leetcode-cn.com/problems/di-yi-ge-zhi-chu-xian-yi-ci-de-zi-fu-lcof/solution/mian-shi-ti-50java-shi-yong-shu-zu-dai-ti-ha-xi-bi/
public char firstUniqChar1(String s) {
if ("".equals(s)) return ' ';
char[] arr = s.toCharArray();
int[] res = new int[128];
for(char c : arr){
res[c]++;
}
for (char c : arr){
if (res[c] == 1) return c;
}
return ' ';
}