美文网首页Leetcode算法算法提高之LeetCode刷题
[剑指offer] 第一个只出现一次的字符

[剑指offer] 第一个只出现一次的字符

作者: 繁著 | 来源:发表于2018-07-15 09:11 被阅读1次

    本文首发于我的个人博客:尾尾部落

    题目描述

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

    解题思路

    先在hash表中统计各字母出现次数,第二次扫描直接访问hash表获得次数。也可以用数组代替hash表。

    参考代码

    HashMap

    import java.util.HashMap;
    public class Solution {
        public int FirstNotRepeatingChar(String str) {
            int len = str.length();
            if(len == 0)
                return -1;
            HashMap<Character, Integer> map = new HashMap<>();
            for(int i = 0; i < len; i++){
                if(map.containsKey(str.charAt(i))){
                    int value = map.get(str.charAt(i));
                    map.put(str.charAt(i), value+1);
                }else{
                    map.put(str.charAt(i), 1);
                }
            }
            for(int i = 0; i < len; i++){
                if(map.get(str.charAt(i)) == 1)
                    return i;
            }
            return -1;
        }
    }
    
    

    数组

    public class Solution {
        public int FirstNotRepeatingChar(String str) {
            int len = str.length();
            if(len == 0)
                return -1;
            char [] s = str.toCharArray();
            int [] m = new int[256];
            for(int i = 0; i < len; i++){
                m[s[i]]++;
            }
            for(int i = 0; i < len; i++){
                if(m[s[i]] == 1)
                    return i;
            }
            return -1;
        }
    }
    

    相关文章

      网友评论

        本文标题:[剑指offer] 第一个只出现一次的字符

        本文链接:https://www.haomeiwen.com/subject/unoupftx.html