Leetcode: Longest Substring Without Repeating Characters

来源:互联网 发布:黑马程序员高清壁纸 编辑:程序博客网 时间:2024/05/17 04:26

Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.

最长非重复子串,感觉可以用DP,没想出来。。。

瞎写,一个很复杂的,虽然也通过了。

class Solution {public:    int lengthOfLongestSubstring(string s) {        int index;        int max_length = 0, length = 0;        vector<int> used(26, -1);        for (int i = 0; i < s.size(); ++i) {            index = s[i] - 'a';            if (used[index] != -1) {                for (int j = 0; j < 26; ++j) {                    if (j != index && used[j] < used[index]) {                        used[j] = used[index];                    }                }            }                        length = i - used[index];            if (length > max_length) {                max_length = length;            }            used[index] = i;        }                return max_length;    }};
讨论区看到简单的,用两个变量指示非重复子串的起始位置。

class Solution {public:    int lengthOfLongestSubstring(string s) {        bool used[26] = {false};        int i = 0, j = 0;        int index, max_length = 0;        for (; j < s.size(); ++j) {            index = s[j] - 'a';            if (used[index]) {                max_length = max(max_length, j - i);                while (s[i] != s[j]) {                    used[s[i] - 'a'] = false;                    ++i;                }                ++i;            }            else {                used[index] = true;            }        }        max_length = max(max_length, j - i);                return max_length;    }};

===============第二次==================

class Solution {public:    int lengthOfLongestSubstring(string s) {        int max_length = 0;        char exists[256] = {0};        int i = 0;        int start = 0;        for (; i < s.size(); ++i) {            if (exists[s[i]] > 0) {                max_length = max(max_length, i - start);                while (s[start] != s[i]) {                    exists[s[start++]] = 0;                }                ++start;            }            exists[s[i]] = 1;        }                max_length = max(max_length, i - start);        return max_length;    }};


0 0
原创粉丝点击