首页 > 其他 > 详细

[Leetcode 3, Medium] Longest Substring Without Repeating Characters

时间:2015-08-13 14:17:23      阅读:176      评论:0      收藏:0      [点我收藏+]

Problem:

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.

Analysis:

The key of the solution of this problem is in how to find out the new start of a substring without repeated characters. The straightforward way is to set the new start to be the next position of the repeated character. This is because the substrings start from the old start to the repeated character will not be a valid solution (they contain the substring starts and ends by the repeated character which imply the length of substring will not be over the current substring). The tricky part of the solution is the using of hash table. The hash table takes the index of a character appears in the string. Only the indices after the start index of every round of loop are meaningful in the determination of a substring is valid. Then, we do not need to build a new hash table in every round.

Code:

C++:

 

 1     int lengthOfLongestSubstring(string s) {
 2         if(s.size() <= 1)
 3             return s.size();
 4 
 5         int start = 0;
 6         int max_len = 1;
 7         vector<int> hash(256, -1);
 8         hash[s[start]] = start;
 9         for(int i = 1; i < s.size(); ++i) {
10             if(hash[s[i]] != -1 && hash[s[i]] >= start)
11                 start = hash[s[i]] + 1;
12                 
13             hash[s[i]] = i;
14             
15             if(i - start + 1 >= max_len)
16                 max_len = i - start + 1;
17         }
18 
19         return max_len;
20     }

 

[Leetcode 3, Medium] Longest Substring Without Repeating Characters

原文:http://www.cnblogs.com/fanwu/p/4727004.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!