To prove safety Offer-33. The first character appears only once (C ++ / Java)

topic:

In one string (0 <= length of the string <= 10000, all of the alphabet) find a first character appears only once, and returns to its position, or -1 if not (case-sensitive).

analysis:

Traversal string, Hashmap using the stored values ​​for each character appears, and then traverse the string, returns to the first character index value 1.

program:

C++

class Solution {
public:
    int FirstNotRepeatingChar(string str) {
        for(int i = 0; i < str.size(); ++i){
            m[str[i]]++;
        }
        for(int i = 0; i < str.size(); ++i){
            if(m[str[i]] == 1)
                return i;
        }
        return -1;
    }
private:
    map<char, int> m;
};

Java

import java.util.*;
public class Solution {
    public int FirstNotRepeatingChar(String str) {
        for(int i = 0; i < str.length(); ++i) {
            if(map.containsKey(str.charAt(i))){
                int count = map.get(str.charAt(i));
                map.put(str.charAt(i), ++count);
            }
            else {
                map.put(str.charAt(i), 1);
            }
        }
        for(int i = 0; i < str.length(); ++i) {
            if(map.get(str.charAt(i)) == 1) {
                return i;
            }
        }
        return -1;
    }
    private HashMap<Character, Integer> map = new HashMap<>();
}

 

Guess you like

Origin www.cnblogs.com/silentteller/p/11980439.html