[leetcode]03 longest substring without repeating
来源:互联网 发布:英雄无敌3 数据修改 编辑:程序博客网 时间:2024/06/07 13:52
Description:
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.
Solution
class Solution {public: int lengthOfLongestSubstring(string s) { int len = s.size(); int max = 0; int index[128] = { 0 }; if (len == 0) return 0; for (int j = 0,i = 0; j < len; j++) { if(i<index[s[j]]) i = index[s[j]]; //i = Math.max(index[s[j]], i ); if (max < j - i + 1) max = j - i + 1; //max = Math.max(j - i + 1, max); index[s[j]] = j + 1; } return max; }};
Discussion
首先,暴力解决肯定是可以的,但是可能会超时。脑子里第一个跳出来的想法就是暴力解决,用i,j
记录不重复子串的头和尾,用max
记录字串最长大小,从头到尾扫描。但是在中途会多次重复扫描,这样的效率比较低。
当然了,最好的办法肯定是从头到尾只扫描一次,那除了头和尾两个指针指向的字母,每次我们可以对比是否相等,但是我们如何记录其他出现过的字母呢?
所以在这里可以构建一个映射关系,用一个数组,将当前的字母和其在字符串中的位置存储起来,在每次遇到一个字母的时候,都保存其序号,当下次遇到一样的字母,这个位置就会被刷新,子串头部的位置就可以根据这个来变化,同时在过程中记录最长子串的位置。
赞美一下小可爱,昨晚耐心给我讲解。
阅读全文
0 0
- LeetCode 03: Longest Substring Without Repeating Characters
- [leetcode]03 longest substring without repeating
- 《leetcode》longest-substring-without-repeating
- LeetCode OJ 03 Longest Substring Without Repeating Characters
- leetcode-03-Longest Substring Without Repeating Characters-python
- LeetCode: Longest Substring Without Repeating Characters
- LeetCode Longest Substring Without Repeating Characters
- LeetCode: Longest Substring Without Repeating Characters
- [Leetcode] Longest Substring Without Repeating Characters
- leetcode 23: Longest Substring Without Repeating Characters
- [LeetCode] Longest Substring Without Repeating Characters
- LeetCode 3 - Longest Substring Without Repeating Characters
- [LeetCode]Longest Substring Without Repeating Characters
- leetcode Longest Substring Without Repeating Characters
- 【leetcode】 Longest Substring Without Repeating Characters
- LeetCode-Longest Substring Without Repeating Characters
- [LeetCode] Longest Substring Without Repeating Characters
- [LeetCode] Longest Substring Without Repeating Characters
- Python numpy(ndarray 随机数组 常用操作 线性方程组和矩阵运算)
- 疯狂java学习笔记(三)
- Java实现-将普通表达式转换成逆波兰表达式并计算
- 聊聊服务化
- Android PendingIntent的getActivity()、getBroadcast()、getService()方法的区别
- [leetcode]03 longest substring without repeating
- 如何使用C语言判断网站、服务器是否通畅
- Docker学习总结
- Ubuntu14.04环境下配置TFTP服务器
- Git 服务器搭建与客户端安装
- Python的for…else和while…else语法
- codeforce 1C Ancient Berland Circus
- Android 异步任务:AsyncTask深入探讨
- HDU