首页 > 代码库 > 387. First Unique Character in a String

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.

思路:利用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;            }}

 

387. First Unique Character in a String