字符串中的第一个唯一字符
From process-oriented thinking to object-oriented thinking
Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1.
Example
s = "leetcode"
return 0.
s = "loveleetcode",
return 2.
Note:
You may assume the string contain only lowercase letters.
我的( 2 ms )
public int firstUniqChar(String s) { int len = s.length(); for (char k = 'a'; k <= 'z'; k++) { int p1 = s.indexOf(k);// -1 不存在 int p2 = s.lastIndexOf(k); if (p1 == p2 && p1 != -1) { len = Math.min(len, p1); } } if (len == s.length()) { return -1; } return len; } }
从字母而不是数组开始扫描。
官方
public int firstUniqChar(String s) { HashMap<Character, Integer> map = new HashMap<Character, Integer>(); int n = s.length(); for(int i = 0; i<n; i++){ char c = s.charAt(i); map.put(c, map.getOrDefault(c,0)+1); } for(int j = 0; j<n;j++){ if(map.get(s.charAt(j)) == 1){ return j; } } return -1; }