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

LeetCode: Longest Substring Without Repeating Characters 题解

时间:2014-05-30 23:46:09      阅读:453      评论:0      收藏:0      [点我收藏+]

标签:c   style   class   blog   code   java   

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.

题解:

使用贪心策略,Hash记录字符上一次出现的位置,并记录起点。

每次更新的时候,记得将start checkpoint 之间出现的字符location清空,以免重复。

bubuko.com,布布扣
 1 class Solution {
 2 public:
 3     int lengthOfLongestSubstring(string s) {
 4         int location[128],i,index,j;
 5         for(i=0;i<128;i++) location[i]=-1;
 6         int start=0,maxLength=0,templ=0;
 7         for(i=0;i<s.size();i++)
 8         {
 9              index = s[i];
10              if(location[index]== -1)
11                  templ++;
12              else
13              {
14                  if(templ>maxLength)
15                  {
16                       maxLength = templ;
17 //                      cout<<s.substr(start,templ)<<endl;
18                  }
19                  for(j=start;j<location[index];j++)
20                      location[s[j]]=-1;
21                  templ =templ - (location[index]-start);
22                  start = location[index]+1;
23              }
24              location[index]=i;
25         }
26         if(i==s.size() && templ>maxLength) maxLength=templ; 
27         return maxLength;         
28     }
29 };
bubuko.com,布布扣

转载请注明出处: http://www.cnblogs.com/double-win/

LeetCode: Longest Substring Without Repeating Characters 题解,布布扣,bubuko.com

LeetCode: Longest Substring Without Repeating Characters 题解

标签:c   style   class   blog   code   java   

原文地址:http://www.cnblogs.com/double-win/p/3761509.html

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