题目

大致思路
- 说明了字符串,因此需要一个26位int返回值的数组,存放26个字母。
- 遍历字符串,将该数组中的对应字母的出现频率存入数组Freq
- 再次顺序遍历进行判断即可,出现的第一个Freq值为1的索引,返回即可。
- 若遍历完找不到,则返回-1。
代码实现
package com.immunize.leetcode.firstdifferent;
public class FirstUniqChar {
public int firstUniqChar(String s) {
int freq[] = new int[26];
for (int i = 0; i < s.length(); i++)
freq[s.charAt(i) - 'a']++;
for (int i = 0; i < s.length(); i++)
if (freq[s.charAt(i) - 'a'] == 1)
return i;
return -1;
}
}
---------------------------------------------------------------------------------------
package com.immunize.leetcode.firstdifferent;
public class FirstUniqCharTest {
public static void main(String[] args) {
FirstUniqChar fuc = new FirstUniqChar();
System.out.println(fuc.firstUniqChar("unique"));
System.out.println(fuc.firstUniqChar("immunize"));
}
}