Fork me on GitHub

LeetCode之387. First Unique Character in a String

--------------------------------------------------

 

最开始的想法是统计每个字符的出现次数和位置,如下:

 

AC代码:

public class Solution {
    
    public int firstUniqChar(String s) {
        Count c[]=new Count[26];
        for(int i=0;i<s.length();i++){
            int index=s.charAt(i)-'a';
            if(c[index]==null) c[index]=new Count(i);
            c[index].count++;
        }
        int min=s.length();
        for(int i=0;i<c.length;i++){
            if(c[i]!=null && c[i].count==1 && c[i].firstIndex<min) min=c[i].firstIndex;
        }
        return min==s.length()?-1:min;
    }
    
    private class Count{
           int count;
           int firstIndex;
           public Count(int firstIndex){
               this.firstIndex=firstIndex;
           }
    }
}

 

但是这样子代码略显拖沓,干脆只记录字符的出现次数,然后再从头扫描如果出现次数为1就表明这是要找的位置了,代码如下:

 

AC代码:

public class Solution {
    
    public int firstUniqChar(String s) {
        int c[]=new int[26];
        for(int i=0;i<s.length();i++) c[s.charAt(i)-'a']++;
        for(int i=0;i<s.length();i++) if(c[s.charAt(i)-'a']==1) return i;
        return -1;
    }
    
}

 

题目来源: https://leetcode.com/problems/first-unique-character-in-a-string/

posted @ 2016-10-25 23:03  CC11001100  阅读(208)  评论(0编辑  收藏  举报