码迷,mamicode.com
首页 > 其他好文 > 详细

[leetcode] Longest Substring Without Repeating Characters

时间:2015-03-05 16:15:49      阅读:104      评论:0      收藏:0      [点我收藏+]

标签:

Longest Substring Without Repeating Characters

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.
 
思路:
max = 0
s = "abcabcbb";
sub = "";
1, sub = a;   max = 1;
2, sub = ab;   max = 2;
3, sub = abc;  max = 3;
4, sub = bca;    max = 3;
5, sub = cab;    max = 3;
6, sub = abc;    max = 3;
7, sub = cb;(因为abc中含有b,所以新的子串为原来子串b之后的字符串加上重复的那个字符,及取abc的c字符串加上重复的那个字符b,构成新的sub字符串cb)  max = 3;
8, sub = b;(理由同上) max = 3;
 
 1 class Solution
 2 {
 3 public:
 4   int lengthOfLongestSubstring(string s)
 5   {
 6     int max = 0;
 7     string sub = "";
 8 
 9     for(int i = 0; i < s.size(); i++)
10     {
11       if(string::npos == sub.find(s[i]))
12         sub += s[i];
13       else
14         sub = sub.substr(sub.find(s[i]) + 1) + s[i];
15 
16       max = max >= sub.length() ? max : sub.length();
17     }
18     return max;
19   }
20 };

 

[leetcode] Longest Substring Without Repeating Characters

标签:

原文地址:http://www.cnblogs.com/lxd2502/p/4316081.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!