The first time the character appears only (24)

topic

[In one string (0 <= length of the string <= 10000, all of the alphabet) found in the first character only occurs once, and returns to its position, or -1 if not (case sensitive) ]


Method One: simple self hashTable

1, analysis
(1), each character is an idea were compared with the following character, and if not it is the same as the character. Time complexity of this method is O ( n 2 ) O (n ^ 2) . A method may be employed to make use of space for time. Create an array used to store the number of times each character appears, at the same time establish the mapping between the strings and arrays. After the number of times each character appears complete statistics, and then traverse the string can get the number of times each character appears. This method requires two traverses the string, the time complexity is O ( n ) O (n) .
(2), when the statistical number of occurrences of each character, may be ASCll code corresponding to the character count for the index array elements, the array is stored ASCll code number corresponding to the characters appear. Because the char character size one byte, i.e. 8-bit binary, which can be represented by 2 8 = 256 2^8=256 characters, so you can save the results of the statistics with an array of length 256.
2, the code

class Solution {
public:
    int FirstNotRepeatingChar(string str) {
        int len=str.size();
        if(len==0)
            return -1;
        const int tableSize=256;
        int *hashTable=new int[tableSize];
        // 第一次遍历统计每个字符出现的次数,并保存该次数在对应的位置上
        for(int i=0;i<len;++i)
        {
            hashTable[str[i]]++;
        }
        // 第二次遍历查找出对应的元素
        for(int j=0;j<len;++j)
        {
            if(hashTable[str[j]]==1)
            {
                return j;
            }
        }
        return -1;
    }
};

Method two: using the STL map

class Solution {
public:
    int FirstNotRepeatingChar(string str) {
        int len=str.size();
        if(len<=0)
            return -1;
        map<char,int> m;
        for(int i=0;i<len;++i)
        {
            m[str[i]]++;
        }
        
        for(int j=0;j<len;++j)
        {
            if(m[str[j]]==1)
                return j;
        }
        
        return -1;
    }
};
Published 213 original articles · won praise 48 · views 110 000 +

Guess you like

Origin blog.csdn.net/Jeffxu_lib/article/details/104766647