题目摘要
给定一个字符串,返回第一个没有重复的字母的下标,如果不存在,返回-1。假设字符串中只含有小写字母。
解法
两个指针slow=0,fast=1;fast先走,并将经过的字母记录下来,直到c[fast] == c[slow],然后slow开始走,直到走到下一个没有记录过两次及以上的字母,然后fast赋为fast+1或slow+1中较大的那个。
public class Solution {
public int firstUniqChar(String s) {
if (s == null || s.length() == 0)
return -1;
if (s.length() == 1)
return 0;
int[] letters = new int[26];
for (int i = 0; i < 26; i++) {
letters[i] = 0;
}
char[] c = s.toCharArray();
int slow = 0, fast = 1;
letters[c[slow] - 'a'] = 1;
while (fast < c.length) {
while (c[fast] != c[slow]) {
letters[c[fast++] - 'a']++;
if (fast == c.length)
return slow;
}
letters[c[fast] - 'a']++;
while (++slow < c.length) {
if (letters[c[slow] - 'a'] <= 1) {
letters[c[slow] - 'a']++;
break;
}
}
if (fast < slow)
fast = slow + 1;
else
fast++;
}
return slow == c.length ? -1 : slow;
}
}
注意
*循环之前,现将第一个字母对应的数组位置加一
可问问题
原题
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.