question:
在一个字符串(0<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置, 如果没有则返回 -1(需要区分大小写).
解法一:map
思路: 我是个笨逼
import java.util.*;
public class Solution {
public int FirstNotRepeatingChar(String str) {
if(str==null||str.length()==0) return -1;
HashMap<Character,Integer> map = new HashMap<>();
for(int i=0;i<str.length();i++){
if(map.containsKey(str.charAt(i))){
int count = map.get(str.charAt(i));
map.put(str.charAt(i),++count);
}else{
map.put(str.charAt(i),1);
}
}
for(int i=0;i<str.length();i++){
if(map.get(str.charAt(i))==1) return i;
}
return -1;
}
}
解法二:数组
思路: a-z的ascii值97-122,A-Z对应的ascii码为65-90
public class Solution {
public int FirstNotRepeatingChar(String str) {
int[] words = new int[58];
for(int i = 0;i<str.length();i++){
words[((int)str.charAt(i))-65] += 1;
}
for(int i=0;i<str.length();i++){
if(words[((int)str.charAt(i))-65]==1)
return i;
}
return -1;
}
}