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.
public class Solution { public int firstUniqChar(String s) { char str[] = s.toCharArray(); int count[] = new int[26]; for(int i =0;i<s.length();i++){ count[str[i]-'a']++; } for(int j=0;j<s.length();j++){ if(count[str[j]-'a']==1){//写的时候犯了个小错误 不应该从counter里面遍历 因为是string里面第一个出现的 所以这里要遍历string return j; }
} return -1; } }
看到一个神奇的用hash表的做法 这个是西加加
- class Solution {
- public:
- int firstUniqChar(string s) {
- if(s.size()==0) return -1;
- unordered_map<char, int> hash;
- for(auto ch: s) hash[ch]++; //这里应用了auto类型说明符 ch为计数变量 s是对象 自动推算变量的类型 也就是针对s中的每一个字符进行操作
- //让map中key为对应字符的值加一
- for(int i = 0; i < s.size(); i++) if(hash[s[i]]==1) return i;
- return -1;
- }
- };