003.Longest Substring Without Repeating Characters
in LeetCode with 0 comment

003.Longest Substring Without Repeating Characters

?> with 0 comment

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.

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        int m[256] = { 0 }, res = 0, left = 0;
        for (int i = 0; i < s.size(); ++i) {
            if (m[s[i]] == 0 || m[s[i]] < left) { //元素虽重复,但是出现在最左边的左边
                res = max(res, i - left + 1);
            }
            else {
                left = m[s[i]];
            }
            m[s[i]] = i + 1;//第几位
        }
        return res;
    }
};

int main() {
    Solution test;
    cout << test.lengthOfLongestSubstring("abbca");
    return 0;
}
Responses

From now on, bravely dream and run toward that dream.
陕ICP备17001447号·苏公网安备 32059002001895号