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

LeetCode 3. Longest Substring Without Repeating Characters

时间:2017-10-24 17:09:39      阅读:161      评论:0      收藏:0      [点我收藏+]

标签:bsp   res   div   out   ash   代码   leetcode   变量   char   

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.

首先建立一个256位大小的整型数组来表示哈希表,定义两个变量res和left,res记录最长无重复子串的长度,left记录最长无重复子串的起始位置。

然后遍历该字符串,对于每一个遍历到的字符,如果哈希表中该字符对应的值为-1, 则说明没有遇到过该字符,此时将该字符加入到最长无重复子串中,长度为i - left + 1, i为遍历到字符的位置。

还有一种情况也需要记录,当哈希表中的值小于left,这是由于此时出现过重复字符,但是left的位置更新了。

c++代码

 1 class Solution {
 2 public:
 3     int lengthOfLongestSubstring(string s) {
 4         vector<int> hash(256, -1);
 5         int left = 0;
 6         int res = 0;
 7         for(int i = 0; i < s.size(); ++ i)
 8         {
 9             if(hash[s[i]] == -1 || left > hash[s[i]])
10                 res = max(res, i - left + 1);
11             else
12                 left = hash[s[i]] + 1;
13             hash[s[i]] = i;
14         }
15         return res;
16     }
17 };

 

LeetCode 3. Longest Substring Without Repeating Characters

标签:bsp   res   div   out   ash   代码   leetcode   变量   char   

原文地址:http://www.cnblogs.com/xjtuchenpeng/p/7724349.html

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