leetcode 刷题题解(c++) 3. Longest Substring Without Repeating Characters (快慢指针,字符hash)

来源:互联网 发布:非诚勿扰全灭灯的软件 编辑:程序博客网 时间:2024/06/01 07:59

Given a string, find the length of the longest substring without repeating characters.

Examples:

Given "abcabcbb", the answer is "abc", which the length is 3.

Given "bbbbb", the answer is "b", with the length of 1.

Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring"pwke" is a subsequence and not a substring.

解法:

class Solution {private:    bool canUse[256];public:    int lengthOfLongestSubstring(string s) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        memset(canUse, true, sizeof(canUse));                int count = 0;        int ret = 0;        for(int i = 0, j = 0; i < s.size(), j < s.size(); j++)        {            if (canUse[s[j]])            {                canUse[s[j]] = false;                count++;            }            else            {                ret = max(ret, count);                while (true) {                    if(s[i] == s[j]) {                        canUse[s[i]] = false;                        i ++;                        break;                    } else {                        canUse[s[i]] = true;                        i ++;                    }                }                count = j -i + 1;            }        }        ret = max(ret, count);        return ret;    }};


0 0
原创粉丝点击