剑指 Offer 50. 第一个只出现一次的字符

class Solution {
    public char firstUniqChar(String s) {
        int len = s.length();
        Set<Character> set = new HashSet<>();
        for(int i = 0;i<len;i++){
            char ch = s.charAt(i);
            if(!set.contains(ch)) {
                if (!s.substring(i + 1).contains(s.substring(i, i + 1))) {
                    return ch;
                } else {
                    set.add(ch);
                }
            }
        }
        return ' ';
    }
}

 

 

public char firstUniqChar(String s) {
        int index = -1;
        for (char c = 'a';c <= 'z'; c++) {
            int cur = s.indexOf(c);
            if(cur != -1 && cur == s.lastIndexOf(c)) {
                index = index == -1 ? cur : Math.min(index, cur);
            }
        }
        return index == -1 ? ' ' : s.charAt(index);
    }

 

posted @ 2020-08-21 11:09  欣姐姐  阅读(211)  评论(0)    收藏  举报