标签:
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.
我的第一种方案,
用一个变量LL记录从0到i-1位置中,以s[i-1]为末尾的substring的长度,
目标是计算L,也就是从0到i位置中,以s[i]为末尾的substring的长度。
递推关系也很简单,从s[i]开始回溯LL个位置,观察有没有字符与s[i]相同,如果相同则跳出回溯。回溯到的字符的个数就是L。
整个递推关系中用max来统计L的最大长度。
class Solution { public: int lengthOfLongestSubstring(string s) { int l=(int)s.length(); if(l==0) return 0; int L,LL; //LL represents the previous substring length //L represents the current substring length L=LL=1; int max=0; for(int i=1;i<l;i++) { int count=1; for(int j=i-1;j>=i-LL;j--) { if(s[j]!=s[i]) count++; else break; } L=count; if(max<L) max=L; LL=L; } return max; } };
运算时间打败了40%的代码
LeetCode|Longest Substring Without Repeating Characters
标签:
原文地址:http://www.cnblogs.com/liluyu/p/5601109.html