LeetCode:Longest Substring Without Repeating Characters

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;
    }
};

 

posted @ 2016-03-04 09:53  翎飞蝶舞  阅读(135)  评论(0编辑  收藏  举报