3.LongestSubstringWithoutRepeatingCharacters

来源:互联网 发布:淘宝网店衣服货源 编辑:程序博客网 时间:2024/06/13 08:44

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 <unordered_map>#include <algorithm>int LongestSubstringWithoutRepeatingCharacters::lengthOfLongestSubstring1(string s){    int result = 0;    for (int i = 0; i < s.length(); i++)    {        for (int j = i; j < s.length(); j++)        {            // 判断长度已经子字符串中是否包含重复字符            if ((j - i + 1) > result & isWithoutRepeatingCharacters(s.substr(i, j - i + 1)))            {                result = j - i + 1;            }        }    }    return result;}bool LongestSubstringWithoutRepeatingCharacters::isWithoutRepeatingCharacters(string s){    // 哈希表的方式记录是否有重复字符    unordered_map<int, bool> hash;    for (int i = 0; i < s.length(); i++)    {        if (hash.find(s[i]) != hash.end())        {            return false;        }        else        {            hash[s[i]] = true;        }    }    return true;}

不用说OJ超时。

解法二:

int LongestSubstringWithoutRepeatingCharacters::lengthOfLongestSubstring2(string s){    // 256个字符的列表,初始化为-1    vector<int> dict(256, -1);    int maxLen = 0, start = -1;    for (int i = 0; i < s.size(); i++)    {        if (dict[s[i]] > start)            // 遇到重复的字符,重置start            start = dict[s[i]];        // 标记该字符在原字符串中的位置到字符列表中,便于计算最长长度        dict[s[i]] = i;        maxLen = max(maxLen, i - start);    }    return maxLen;}

测试代码:

    LongestSubstringWithoutRepeatingCharacters longestSubstringWithoutRepeatingCharactersongest;    string s = "abcdabcbb";    int result = longestSubstringWithoutRepeatingCharactersongest.lengthOfLongestSubstring2(s);    cout << result << "\n";    cout << endl;
1 0
原创粉丝点击