leetcode.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.

Note: You may assume the string contain only lowercase letters.


public class Solution {
    public int firstUniqChar(String s) {
        if(s==null||s.equals("")) return -1; //字符串爲 null或者“”直接返回-1,好多程序都應該這樣首先驗證特殊情況
        char[] cs = s.toCharArray();<span style="white-space:pre">		</span>//字符串轉換爲字符數組,關鍵!
        boolean[] csb = new boolean[cs.length];//對應數組的標誌,每次檢測到後面又重複的將重複的標識置爲true,循環遇到時跳過
        if(cs.length == 1) return 0;
        boolean isLast = false;
        for(int i=0; i < cs.length-1; i++){
            if(csb[i]==true) continue; <span style="white-space:pre">		</span>//已經被前面檢測到重複,跳過本次循環,進行下一次。不這樣好像有個很長的輸入會超時
            boolean isTwo = false;
            for(int j=i+1; j< cs.length; j++){
//                if(csb[j]==true) continue;
                if( cs[i] == cs[j] ){
                    csb[j] = true;<span style="white-space:pre">		</span>
                    isTwo = true;<span style="white-space:pre">		</span>//每次i循環檢查是否有相同的,有相同就置爲true,否則後面檢查到false就說明沒有相同的,就return
                    if(j == cs.length-1) isLast = true; //因爲每次j從i+1開始循環,也就是不檢測前面的,最後一個不好檢測,也用了一個flag
                }

            }
            if(isTwo == false){
                return i;
            }
        }
        if(isLast == false) return cs.length-1;
        return -1;
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章