带字符串检查的哈希表

时间:2015-02-13 23:17:09

标签: c++ hashtable

我正在研究一些代码检查字符串中字符的重复。以下是我在某处找到的答案。

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        int hash[256];
        for(int i=0; i<256; i++) hash[i] = -1;
        int start = 0, ans = 0;
        int i;
        for(i=0; i<s.size(); i++){
            if( -1 != hash[ s[i] ] ){
                if(ans < i-start) ans = i-start;//update max length
                for(int j=start; j<hash[ s[i] ]; j++) hash[j] = -1;
                if(hash[ s[i] ] + 1  > start )
                   start = hash[ s[i] ] +1;//update start if repeat happen
            }
            hash[ s[i]] = i;
        }
        if(ans < i-start) ans = i-start;
        return ans;
    }
};

它有效,而且大部分地方都很清楚。我只是困惑了几行。

if( -1 != hash[ s[i] ] ){
                if(ans < i-start) ans = i-start;//update max length
                for(int j=start; j<hash[ s[i] ]; j++) hash[j] = -1;
                if(hash[ s[i] ] + 1  > start )
                   start = hash[ s[i] ] +1;
            }
            hash[ s[i]] = i;

以下是问题:

(1)为什么检查hash [s [i]]!= - 1? s [i]是字符串中的字符,上面的代码显示hash [i],i是0-256。

(2)我很困惑

for(int j=start; j<hash[ s[i] ]; j++) hash[j] = -1;
                    if(hash[ s[i] ] + 1  > start )
                       start = hash[ s[i] ] +1;

请做什么?

1 个答案:

答案 0 :(得分:1)

那不是哈希表。 hash变量是一个int数组,由字符串中char的ascii代码索引,因此hash [s [i]]其中s [i] =='A'是hash [63]。因此,它的作用是将字符的位置存储在由字符代码索引的数组中。

hash[s[i]]!=-1检查是否出现了字符

for(int j=start; j From start to the current position of the character set hash[position] to -1. This must be either buggy or misintended as it mixes the character-based index of hash with the positional nature of j.

if(hash[ s[i] ] + 1 > start ) start = hash[ s[i] ] +1; 如果当前字符的位置在当前字符后的开始设置开始之后。

相关问题