剑指offer33_第一个只出现一次的字符

题目描述

在一个字符串(0<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置, 如果没有则返回 -1(需要区分大小写).

代码及注释:

//旧版剑指offer返回的是这个字符本身
//用hashtable存储字符串,key=字母,value=次数
//第一次遍历用来统计次数,第二次遍历哈希表找value=1的值
//但这样的话,无法知道那个字符的具体坐标
//新版的剑指offer要求返回它的位置
//尝试把第二遍遍历用在字符串上,在哈希表中查找对应的value,如果是1则输出其坐标
import java.util.HashMap;    
public class Solution {
    public int FirstNotRepeatingChar(String str) {
        HashMap<Character,Integer> map = new HashMap<Character,Integer>();
        char[] s=str.toCharArray();
        for(int i=0;i<s.length;i++){
            if(map.containsKey(s[i])){
                map.put(s[i],map.get(s[i])+1);//HashMap的value值是不能改变的,但可以被覆盖
            }
            else{
                map.put(s[i],1);
            }
        }
        for(int j=0;j<s.length;j++){
            if(map.get(s[j])==1){
                return j;
            }
        }
        return -1;
    }
}

但是这样时间复杂度比较高。。。

参考https://blog.csdn.net/justlikeu777/article/details/85066308 中的思路:
说一下解题思路哈,其实主要还是hash,利用每个字母的ASCII码作hash来作为数组的index。首先用一个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++){
            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;
    }
}

猜你喜欢

转载自blog.csdn.net/lilililililydia/article/details/88944009