【编程】leetcode_longest substring without repeating characters

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

转载于:https://www.cnblogs.com/visong/p/4195795.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值