首页 > 代码库 > LeetCode3:Longest Substring Without Repeating Characters
LeetCode3:Longest Substring Without Repeating Characters
题目:
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.
解题思路:
一开始,没看清题目要求,以为是去重,一提交出错才知不是。
只要谈到去重或者无重复之类的词,就应该想到哈希表或bitmap。
这里直接引用网上大牛的解题方法:http://blog.csdn.net/kenden23/article/details/16839757
利用两指针i,j。i走在前,每次到哈希表中查找之前是否出现,没有则将对应位置置1,若出现过,说明开始下一个子串
实现代码:
#include <iostream> #include <string> #include <cstring> using namespace std; /** 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. */ class Solution { public: int lengthOfLongestSubstring(string s) { if(s.empty()) return 0; int len = s.size(); int bitmap[256] = {0}; //memset(bitmap, 0, sizeof(int) * 26); int maxLen = 0; int j = 0; for(int i = 0; i < len; i++) { if(bitmap[s[i]] == 0) { bitmap[s[i]] = 1; } else { maxLen = max(maxLen, i-j); while(s[i] != s[j])//对bitmap进行设置,将重复元素之前的所有元素对应的位置0,因为这些元素不参与下一次字符串 { bitmap[s[j]] = 0; j++; } j++; } } maxLen = max(maxLen, len-j);//for循环退出是因为i =len,所以这里还要判断 return maxLen; } }; int main(void) { string s("wlrbbmqbhcdarzowkkyhiddqscdxrjmowfrxsjybldbefsarcbynecdyggxxpklorellnmpapqfwkhopkmco"); Solution solution; int res = solution.lengthOfLongestSubstring(s); cout<<res<<endl; return 0; }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。