在一个字符串(0<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置, 如果没有则返回 -1(需要区分大小写).(从0开始计数)
没什么捷径就是遍历,用数组来代替map节省空间,就是leetcode387,唯一不同就是把数组的范围提升一下。我想过用map,后来用了两个集合,功能可以,但限定了字符串,用数组更省。
public class Solution {
public int FirstNotRepeatingChar(String str) {
if(str==null || str.length() == 0)return -1;
int[] count = new int[256];
//用一个类似hash的东西来存储字符出现的次数,很方便
for(int i=0; i < str.length();i++)
count[str.charAt(i)]++;
for(int i=0; i < str.length();i++)
if(count[str.charAt(i)]==1)
return i;
return -1;
}
}