387.First Unique Character in a String

Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1.
Examples:

s = "leetcode"
return 0.

s = "loveleetcode",
return 2.

Note:You may assume the string contain only lowercase letters.
这道题和169.Majority Element相似,我们先使用Map的方法
方法一

public int firstUniqChar(String s) {
            int result =-1;
            Map<Character,Integer> map = new HashMap();
            for(int i = 0; i < s.length();i++)
            {
                char tmp = s.charAt(i);
                if(!map.containsKey(tmp))
                    map.put(tmp,1);
                else
                    map.put(tmp,map.get(tmp) + 1);
            }
            System.out.println(map);
            for(int i = 0; i < s.length();i++)
            {
                if(map.get(s.charAt(i)) == 1)
                {
                    result= i;
                    break;
                }  
            }
            return result;
        }

方法二
巧妙使用ASCII方法

public int firstUniqChar(String s) {
        int a[] =  new int[26];
        for(int i = 0; i < s.length();i++)
        {
            a[s.chartAt(i)-'a'] ++;
        }
        for(int i = 0; i < s.length();i++)
        {
            if(a[s.chartAt(i)-'a']==1)
                return i;
        }
        return -1;
    }
原文地址:https://www.cnblogs.com/wxshi/p/7683759.html