leetcode4 ---Longest Substring Without Repeating Characters
来源:互联网 发布:winhex linux 编辑:程序博客网 时间:2024/05/17 03:05
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.
题目解析:本题目的含义是在一个字符串中查找不重复的最大子串的问题,返回最大子串的长度。比如“abcabcbb”,最大非重复子串为“abc”,长度为3.“bbbbbb”,最大子串为"b",长度为1.
思路:对于寻找子串的的问题通过枚举遍历所有子串,然后找出最大的子串,该方法的复杂度在N的三次方左右。一直在思考有没有其他可行的方法,对于元素查找的情况,通常会想到hashtable,因为这种方法能够容易处理重复情况且速度快。由于题目中给出的是字母或者数字,根据参考其他方面的分析,把字符串中每个字母的ASCC码值作为table的index,table的具体元素为bool型,在字符串中,如果当前位置以前未出现过该字母,那么就将该子母所对应的table中的元素设置为TRUE,另外需要一个变量记录最大长度。简单的分析入上,参考论坛代码如下:
class Solution {public: 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
- leetcode4 ---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
- 搭建quick-cocos2dx调试环境出错
- 浅谈my_memcpy()函数的实现
- 二哥学算法之归并排序和希尔排序
- javascript语言扩展:可迭代对象(2)
- 让button有边框,或变成圆形
- leetcode4 ---Longest Substring Without Repeating Characters
- 【jQuery】网页文本格式编辑器xheditor
- 黑马程序员——C语言基础(一)C语言简述及关键字
- [Vijos 1049] 送给圣诞夜的礼品 · 矩阵乘法
- 古代智慧与当代爱情 之 《仲夏夜之梦》
- FlowLayout
- 某个年份是否是闰年
- hdu 5191 Building Blocks
- TCP的KeepAlive和HTTP的Keep-Alive