Labels

Thursday, February 19, 2015

Find First Non Repeating Character in String

From http://www.geeksforgeeks.org/given-a-string-find-its-first-non-repeating-character/
Given a string, find the first non-repeating character in it. For example, if the input string is “GeeksforGeeks”, then output should be ‘f’ and if input string is “GeeksQuiz”, then output should be ‘G’.

Naive Thinking: 用一个map去映射字母和出现次数?最后再遍历一遍,第一个出现次数为1的就是输出。可不可以一次遍历?好像可以,用一个指针指向目前最前出现的次数为1的位置。

public char firstNonRepeatingChar(String s){
        int index = 0;
        Map<Character, Integer> map = new HashMap<Character, Integer>();
        for(int i = 0;i < s.length();i++){
            if(!map.containsKey(s.charAt(i))){
                map.put(s.charAt(i), 1);
            }else{
                map.put(s.charAt(i), map.get(s.charAt(i))+1);
                while(index < s.length() && map.containsKey(s.charAt(index)) && map.get(s.charAt(index)) > 1) index++;
            }
        }
        return index<s.length()?s.charAt(index):'0';
    }

No comments:

Post a Comment