Given a string, find the first non-repeating character in it and return it’s index. If it doesn’t exist, return -1.
Examples:
s = "leetcode" return 0. s = "loveleetcode", return 2.
Note: You may assume the string contain only lowercase letters.
这种题有很多类似变种,比如:
- 寻找第一个重复的字符
- 确认String是否全部unique
思路非常容易,无非是:
- 用一个array of boolean 出现重复则false
- 用set,如果放不进去,则是重复的
- 用array of int, 用string.charAt(i) – ‘a’,等到字母,然后计数
那么我现在用第三种方法解决:
public class Solution { public int firstUniqChar(String s) { int unique[] = new int[26]; for(int i=0;i<s.length();i++){ unique[s.charAt(i) -'a'] ++; } for(int i=0;i<s.length();i++){ if(unique[s.charAt(i) -'a']==1){ return i; } } return -1; } }