码迷,mamicode.com
首页 > 其他好文 > 详细

【编程】leetcode_longest substring without repeating characters

时间:2014-12-31 16:05:02      阅读:143      评论:0      收藏:0      [点我收藏+]

标签:

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        char cHash[256];
        int cnt = 0, maxCnt = 0;
        int i, j, k, sSz = s.size();
        char chRep;

        memset(cHash, 0, 256);

        cnt = 1;    // initialization        

        for(i = 0, cHash[0] = 0; i < sSz; )
        {
            cHash[s[i]] = 1;
            for (j = i + 1; j < sSz; j++)
            {
                if (cHash[s[j]] == 0)
                {
                    cnt++;        // increase length
                    cHash[s[j]] = 1;
                }
                else
                {
                    chRep = s[j];
                    break;    // got the same character
                }
            }

            if (cnt > maxCnt)    // renew the maxcnt
            {
                maxCnt = cnt;
            }

            // got the next i index, find where is the chSame
            for (k = j - cnt; k < j; k++)
            {
                if (s[k] == chRep)
                {
                    break;
                }
                cnt--;                // decrease
                cHash[s[k]] = 0;    // delete from hashtable
            }

            i = j;    // i start from the j position
        }

        return maxCnt;
    }
};

思路:

1. 使用char cHash[256]作为hash表来存储某个字符是否已经出现过;

2. 遍历字符串,出现的字符串在hash表中置1;

3. 一旦发现重复出现的字符串,返回当前子串查找,当前子串中在出现字符之前的字符从hash表中删除;

4. 下次循环可以接着子循环的位置继续下去,看上去是两层循环,其实对于整个字符串只会遍历一次。

【编程】leetcode_longest substring without repeating characters

标签:

原文地址:http://www.cnblogs.com/visong/p/4195795.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!