58. Length of Last Word
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.
思路:
找出第一个不重复出现的字母,这题最容易想到的是用一个map记录下每个字母出现的次数,然后根据map去寻找只出现一次的字母的索引。这样做的时间消耗太多,采用另一种思路:题目中的字母默认只会有小写字母,那就可以以
a
-z
来遍历字符串,如果第一次出现的索引下标和最后一次相同,就是结果,然后记录这其中下标最小的。
代码:
java:
class Solution {
/*public int firstUniqChar(String s) {
if (s == null || s.length() == 0) return -1;
HashMap<Character, Integer> count = new HashMap<Character, Integer>();
for (int i = 0; i <s.length(); i++) {
char c = s.charAt(i);
count.put(c, count.getOrDefault(c, 0) + 1);
}
for (int i = 0; i <s.length(); i++) {
if (count.get(s.charAt(i)) == 1) return i;
}
return -1;
}*/
public int firstUniqChar(String s) {
if (s == null || s.length() == 0) return -1;
int res = Integer.MAX_VALUE;
for (char c = 'a'; c <= 'z'; c++) {
if (s.indexOf(c) == -1) continue;
if (s.indexOf(c) == s.lastIndexOf(c))
res = Math.min(res, s.indexOf(c));
}
return res == Integer.MAX_VALUE ? -1 : res;
}
}