Longest Substring Without Repeating Characters
来源:互联网 发布:python 远程兼职 编辑:程序博客网 时间:2024/05/22 03:41
题目:
给一个字符串,找到最长的子串,子串不包括重复字符,例如:"abcabcbb"的最长子串就是"abc",长度为3."bbbbb"的最长子串是"b",长度为1
分析:
用哈希的方法,从前往后扫描一遍,最长子串中的字符不能重复,所以扫描时遇到的字符如果在之前出现过,那么说明此时之前扫描过的字符串有可能是最长的子串。又因为子串不能重复,所以找到之前扫描过的字符串中与当前相等的字符。把字符串中与当前相等字符的前面的一些字符清楚掉。然后两下标同时往前走一步,继续寻找有可能的最长子串
代码:
class Solution {public: int lengthOfLongestSubstring(string s) { unordered_map<char, int> u_map; int n = s.length(); int i = 0, j = 0; int maxLen = 0; while(i < n){ if(u_map.count(s[i])){ maxLen = max(maxLen, i - j); while(s[i] != s[j]){ u_map.erase(s[j]); ++j; } ++i; ++j; }else{ u_map[s[i]] = i; ++i; } } maxLen = max(maxLen, n-j); return maxLen; }};
更简单有效的代码:
int lengthOfLongestSubstring(string s) { int n = s.length(); int i = 0, j = 0; int maxLen = 0; bool exist[256] = { false }; while (j < n) { if (exist[s[j]]) { maxLen = max(maxLen, j-i); while (s[i] != s[j]) { exist[s[i]] = false; i++; } i++; j++; } else { exist[s[j]] = true; j++; } } maxLen = max(maxLen, n-i); return maxLen;}
0 0
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters
- iPhone6分辨率与适配
- dijo. "Y creo que nos merecemos mejor que el secreto." "Yo también
- la puerta con la bisagra draggy se abrió. Una cosa que tenía que hacer. No podía dejarlo sin hacer.
- murmuró. Pero había algo un poco mecánica en su sonrisa
- 远程控制电脑的软件安装很麻烦吗
- Longest Substring Without Repeating Characters
- y las preocupaciones de M sobre la independencia de su unidad se ha ido para siempre. Bond
- 单实例懒汉模式并包保证成功
- OpenGL 矩阵变换
- atravesando el pantano de flecha recta hasta que desapareció en la selva que bordeaba la rama. Lo si
- struts2下list转JSON
- Sql 除法 两个数相除怎么结果为0
- ubuntu 14.04 切换到root权限的方法
- java readme.txt