3.Longest Substring Without Repeating Characters

来源:互联网 发布:商业数据分析报告 编辑:程序博客网 时间:2024/06/03 20:40

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) {        string tmp;        int len;        len = s.empty() ? 0 : 1;        for(int i = 0; i < s.length(); i++){            int pos = tmp.find(s[i], 0);            if(pos == string::npos){                tmp += s[i];            } else {                len = tmp.length() > len ? tmp.length() : len;                tmp.erase(tmp.begin(), tmp.begin() + pos + 1);                tmp += s[i];            }        }        len = tmp.length() > len ? tmp.length() : len;        return len;    }};

参考博客
http://blog.csdn.net/wangyaninglm/article/details/51068831
动态规划思路:

class Solution {public:    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