34.第一个只出现一次的字符
在一个字符串(0<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置, 如果没有则返回 -1(需要区分大小写).
方法1:
解题思路:首先用一个58长度的数组来存储每个字母出现的次数,为什么是58呢,主要是由于A-Z对应的ASCII码为65-90,a-z对应的ASCII码值为97-122,而每个字母的index=int(word)-65,比如g=103-65=38,而数组中具体记录的内容是该字母出现的次数,最终遍历一遍字符串,找出第一个数组内容为1的字母就可以了,时间复杂度为O(n)
public class Solution {
public int FirstNotRepeatingChar(String str) {
int[] words=new int[58];
for(int i=0;i<str.length();i++){
//把字符的ascii-65作为数组的下标
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;
}
}
方法2:有点类似test28
import java.util.LinkedHashMap;
public class Solution {
public int FirstNotRepeatingChar(String str) {
LinkedHashMap<Character,Integer> map =new LinkedHashMap<Character,Integer>();
for(int i=0;i<str.length();i++){
if(map.containsKey(str.charAt(i))){
int time=map.get(str.charAt(i));//获取这个字符
map.put(str.charAt(i),++time);//把这个字符和出现的次数放入键值对里
}else{
map.put(str.charAt(i),1);//这一不说明该字符只出现了一次
}
}
int pos=-1;
int i=0;
for(;i<str.length();i++){
char c=str.charAt(i);
if(map.get(c)==1){
return i;
}
}
return pos;
}
}
这题用啥map没啥区别的……因为他最后又在字符串中遍历了一遍。如果非要用到LinkedHashMap的特性的话,可以先遍历LinkedHashMap找到第一个value为1的key,然后str.indexOf(key)就是所求的结果。