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.

思路:利用ascii建array。扫两遍string,第一遍记录每个char的次数,扫第二遍string,碰到次数为1的直接输出。
public class Solution {
    public int firstUniqChar(String s) {
        if(s.length()==0)
        {
            return -1;
        }
        int[] res=new int[128];
        for(int i=0;i<s.length();i++)
        {
            if(res[s.charAt(i)]==0)
            {
                res[s.charAt(i)]=1;
            }
            else
            {
                res[s.charAt(i)]++;
            }
        }
        for(int i=0;i<s.length();i++)
        {
            if(res[s.charAt(i)]==1)
            {
                return i;
            }
        }
        return -1;
        
    }
}

 

posted on 2016-10-10 05:35  Machelsky  阅读(137)  评论(0)    收藏  举报