Longest Substring Without Repeating Characters from LeetCode
来源:互联网 发布:javascript跳转新页面 编辑:程序博客网 时间:2024/06/01 22:06
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 asubstring, "pwke"
is a subsequence and not a substring.
简言之,找出给定字符串的不含重复字符的子串,返回长度。
先上代码,已通过Online Judge
int result; int head = 0,len = 0;//result是方法的返回值,head是操作的子串的开始位置,len是在已经完成操作的子串中最长的长度char[] data = new char[s.length()];data = s.toCharArray();int[] last = new int[128];for(int i = 0;i < last.length;i++) {last[i] = -1;}for(int i = 0;i < data.length;i++) {if(last[(int)data[i]] >= head) {if((i - head) > len) {len = i - head;}head = last[(int)data[i]] + 1;}last[(int)data[i]] = i;}result = (len > (data.length - head))?len : (data.length - head);return result;
01234567abcbadbc
以上面这个字符串为例,从头开始统计
0号,a未出现过,记录下last[(int)'a'] = 0
1号,b未出现过,记录下last[(int)'b'] = 1
2号,c未出现过,记录下last[(int)'c'] = 2,这时最长子串是012,abc
3号,b曾经在1号出现过,意味着从原来的子串gg了,记录下原来最长的子串长度3,同时统计应该从1号的下一位,2号重新开始,记录下last[(int)'b'] = 2
4号,a曾经在0号出现过,但是我们的子串现在是从2号开始的,所以不会有影响,同时更新last[(int)'a'] = 4
字符串遍历主要关注的就是上面在3号位,4号位发生的故事
另外,因为只有当字符串开始位置变更时才会更新len,所以遍历完成之后要检查一下,如代码倒数第二行。
程序写完之后想着搜索一下有没有更好的解法,发现了另一位仁兄的日志,http://www.51testing.com/html/91/15038991-862324.html ,代码几乎一模一样
- Longest Substring Without Repeating Characters from LeetCode
- 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
- [leetcode] Longest Substring Without Repeating Characters
- LeetCode - Longest Substring Without Repeating Characters
- LeetCode 3: Longest Substring Without Repeating Characters
- leetcode-3:Longest Substring Without Repeating Characters
- 韩信点兵的问题求解方法
- 唯品会的订单分库分表实践总结以及关键步骤
- Android 笔记 读取style文件的属性
- Oracle 中的JOIN
- Windows下多个Python版本共存
- Longest Substring Without Repeating Characters from LeetCode
- HDU 5914 Triangle 【构造】 (2016中国大学生程序设计竞赛(长春))
- 认识css样式(第二部分-文字排版)
- 文章标题
- codeforces723D-Lakes in Berland-DFS
- soekct实践编程1
- Codeforces Round #285 (Div. 2) C Misha and Forest
- 分库分表策略的可实现架构
- 【软件工程】——项目开发计划