3. Longest Substring Without Repeating Characters

Total Accepted: 130742 Total Submissions: 605248 Difficulty: Medium

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.

考虑临界值,字符串为空或长度为1的情况。

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
         if (s.length() == 1)
             return 1;
         else if (s.length() == 0)
             return 0;
         string tmp = "";
         string sub = "";
         int n = 0, len = 0, st = 0;
         for (int i = 0; i<s.length();)
         {
             int k = tmp.find(s[i]);
             if (tmp.find(s[i]) == string::npos)
             {
                 tmp = tmp + s[i];
                 n++;
                 i++;
                 if (len<n)
                 {
                     sub = tmp;
                     len = n;
                 }
             }
             else
             {
                 n = tmp.length() - k;
                 tmp = tmp.substr(k + 1, tmp.length() - k - 1) + s[i];
                 
                 i = i + 1;
             }
         }
         return len;
    }
};

 

相关文章:

猜你喜欢
  • 2021-11-13
  • 2021-07-03
  • 2021-12-05
  • 2021-07-08
  • 2021-12-09
相关资源
相似解决方案