003 Longest Substring Without Repeating Characters [Leetcode]
2015-11-09 14:45
453 查看
题目内容:
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.
解题思路:
顺序遍历,使用hash表记录已经读到过的字母。
由于ASCII码足够表示所有字符了,使用一个长度为128的数组记录出现的下标即可。
每次读到重复的数字时,不重复字符串的起始位置就变为hash表中记录的下标的后一位,并更新最长字符串长度和hash表中记录的当前字母的下标。
时间复杂度为O(n)。
代码:
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.
解题思路:
顺序遍历,使用hash表记录已经读到过的字母。
由于ASCII码足够表示所有字符了,使用一个长度为128的数组记录出现的下标即可。
每次读到重复的数字时,不重复字符串的起始位置就变为hash表中记录的下标的后一位,并更新最长字符串长度和hash表中记录的当前字母的下标。
时间复杂度为O(n)。
代码:
class Solution { public: int lengthOfLongestSubstring(string s) { if(s == "") return 0; int l = 0, r = 0, maxl = 0; unsigned char cset[128]; memset(cset, 0, 128*sizeof(unsigned char)); while(r < s.size()) { if(cset[s[r]] == 0) cset[s[r]] = 1; else { maxl = max(maxl, r - l); while(s[r] != s[l]) { cset[s[l]] = 0; ++ l; } ++ l; } ++ r; } maxl = max(maxl, r - l); return maxl; } };
相关文章推荐
- 聚类算法总结
- Paper: Saliency Mapping Enhanced by Structure Tensor is published
- Mongodb开启与关闭
- 安卓各种资源介绍及使用方法以及工程各文件夹的介绍
- ios修改Navigation的标题的颜色,字体大小,背景颜色等
- js快速分享代码
- Memcached
- Android性能优化典范(A3)--电量优化
- 以树莓派为控制中心的软硬件之开发之脑电波模块
- 手机自动化测试:appium源码分析之bootstrap五
- 第三方接口
- SAP往来重组
- UIMenuController的使用,对UILabel拷贝以及定制菜单 .posted on 2013-03-18 16:20
- 翻译随笔(4)——辞职前该考虑的五个问题
- AJAX+H5 上传文件+进度条
- SPI与ads8345
- crontab详解
- Apache2优化
- php开发工具有哪五款
- Qt发布程序(windows平台)