美文网首页
[Swift LeetCode]3. Longest Subst

[Swift LeetCode]3. Longest Subst

作者: NinthDay | 来源:发表于2016-01-18 23:43 被阅读169次

题目

原题链接
Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.

思路

有点愚 使用了4张hash表......效率不咋地

代码

SWIFT解决方案:

TODO:之后添加

C 语言解决方案:

int lengthOfLongestSubstring(char* s) {
    /// 构建 hash 表来实现
    int len = strlen(s);
    /// 构建四张hash表
    int hash[4] = {0};
    int maxLen = 0;    

    for(int j =0;j<len;j++){
        char *ss = s;
        int llen = 0;
        for (int i = j;i < len; ++i)
        {
            int tableIndex = ss[i] / 32 ; // 应该是0 1 2 3
            int posIndex = ss[i] % 32 ;  // 一张hash表中的位置0-31
            
            if((hash[tableIndex] >> (posIndex) & 0x1) == 0){
            // 说明不存在
                hash[tableIndex] |= 1 << (posIndex);
                llen++;   //计数+1
            }else{
                break;//跳出里边的循环
            }
        }
        if(llen > maxLen){
            maxLen = llen;
        }
        hash[0] = 0 ;//hash 表清零
        hash[1] = 0 ;//hash 表清零
        hash[2] = 0 ;//hash 表清零
        hash[3] = 0 ;//hash 表清零
    }
    return maxLen;
}

相关文章

网友评论

      本文标题:[Swift LeetCode]3. Longest Subst

      本文链接:https://www.haomeiwen.com/subject/gzvkkttx.html