题目描述
在一个字符串(1<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置
第一种方法:利用hashmap能有存键值对的特点,当遍历到当前字符时候,保存该字符的数量。
public int FirstNotRepeatingChar(String str) {
HashMap<Character,Integer> map=new HashMap<>();
char s[]=str.toCharArray();
for(int i=0;i<s.length;i++){
if(map.containsKey(s[i])){
int tmp=map.get(s[i])+1;
map.remove(s[i]);
map.put(s[i],tmp);
}else {
map.put(s[i],1);
}
}
for(int i=0;i<s.length;i++){
if(map.containsKey(s[i])&&map.get(s[i])==1){
return i;
}
}
return -1;
}
第二种方法:借用创建一个拥有很多桶的数组,字符的ascll码为桶的编号。遍历字符串,把当前字符根据它的ascll码装入相应的桶中,桶中元素的个数会累加。
public int FirstNotRepeatingChar1(String str){
if(str==null||str.length()==0){
return -1;
}
int a[]=new int[256];//相当于拥有256个桶的数组。
char s[]=str.toCharArray();
for(int i=0;i<s.length;i++){//把字符串中的元素都放入桶中
a[s[i]]++;//编号为s[i]的桶内元素的个数增加1.
}
for(int j=0;j<s.length;j++){
//遍历字符串,根据字符找到桶,检查桶内的元素个数是否为1,如果是,返回当前字符的索引。
if(a[s[j]]==1){
return j;
}
}
return -1;
}
第三种:
//Insert one char from stringstream
public void Insert(char ch) {
map.put(ch, map.getOrDefault(ch, 0) + 1);
queue.add(ch);
while (!queue.isEmpty() && map.get(queue.peek()) > 1)
queue.poll();
}
//return the first appearence once char in current stringstream
public char FirstAppearingOnce() {
return queue.isEmpty() ? '#' : queue.peek();
}