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

Longest Substring Without Repeating Characters

时间:2014-09-09 11:49:38      阅读:167      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   ar   for   div   sp   log   

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 {
 2 public:
 3     int lengthOfLongestSubstring( string s ) {
 4         int ret = 0, prev = -1, slen = s.length();
 5         for( int i = 0; i < slen; ++i ) {
 6             int k = i;
 7             while( --k > prev && s[k] != s[i] ) { ; }
 8             if( ret < i-k ) { ret = i-k; }
 9             prev = k;
10         }
11         return ret;
12     }
13 };

 

Longest Substring Without Repeating Characters

标签:style   blog   color   io   ar   for   div   sp   log   

原文地址:http://www.cnblogs.com/moderate-fish/p/3960846.html

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