3. Longest Substring Without Repeating Characters

来源:互联网 发布:阿里云域名过户怎么过 编辑:程序博客网 时间:2024/05/22 08:15

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 {public:    int lengthOfLongestSubstring(string s) {        if (s == "") return 0;        int maxLen = 0, index = 0, subLen = 0;        string sub = "";        while (index != s.size()) {            if (sub == "" || sub.find(s[index]) == sub.npos) {                sub += s[index];                index++;                //这里要用subLen记录子串的长度(若不记录,则“c”,"abc"这样的样例会出错)                subLen++;            }            else if (sub.find(s[index]) != sub.npos) {                if (sub.size() > maxLen) {                    maxLen = sub.size();                }                int i = index - 1;                while (i >= 0) {                    if (s[i] == s[index]) {                        index = i + 1;                        break;                    }                    i--;                }                //一定要把sub和subLen重置                sub = "";                subLen = 0;            }        }        return maxLen > subLen ? maxLen : subLen ;    }};

再贴一个别人写的简洁操作:

int lengthOfLongestSubstring(string s) {        vector<int> dict(256, -1);        int maxLen = 0, start = -1;        for (int i = 0; i != s.length(); i++) {            if (dict[s[i]] > start)                start = dict[s[i]];            dict[s[i]] = i;            maxLen = max(maxLen, i - start);        }        return maxLen;    }
阅读全文
0 0
原创粉丝点击