003_LeetCode_3 Longest Substring Without Repeating Characters 题解
来源:互联网 发布:华语网络女歌手排行榜 编辑:程序博客网 时间:2024/06/09 17:24
Descripton
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.
返回一个字符串中,不包含重复元素的连续子序列的长度。
解:
使用HashMap
,以字符串对应的元素作为key,下标作为value。遍历字符串,判断当前元素是否已经存在于哈希表中:
若存在则,删除上次存入的下标以及该下标之前的元素;将当前元素存入哈希表,更新起始的遍历位置和子串长度。
若不存在,则将当前元素存入哈希表,子串长度加一,并于最大子串长度比较。
java代码:
class Solution { public int lengthOfLongestSubstring(String s) { if (s == null) return 0; HashMap<Character, Integer> map = new HashMap<Character, Integer>(); int start = 0, maxLen = 0, subLen = 0; for (int i = 0; i < s.length(); i++) { if (!map.containsKey(s.charAt(i))){ map.put(s.charAt(i), i); subLen++; if (subLen > maxLen) maxLen = subLen; }else { int index = map.get(s.charAt(i)); for (int j = start; j <= index; j++) { map.remove(s.charAt(j)); } map.put(s.charAt(i), i); start = index + 1; subLen = i - index; } } return maxLen; }}
阅读全文
0 0
- 003_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
- 3. Longest Substring Without Repeating Characters题解
- Longest Substring Without Repeating Characters---题解
- [LeetCode]Longest Substring Without Repeating Characters题解
- [Leetcode题解]003 Longest Substring Without Repeating Characters
- LeetCode 003 Longest Substring Without Repeating Characters
- LeetCode-003 Longest Substring Without Repeating Characters
- 【leetcode】003 Longest Substring Without Repeating Characters
- LeetCode 003 Longest Substring Without Repeating Characters
- LeetCode 003-Longest Substring Without Repeating Characters
- [LeetCode]-003-Longest Substring Without Repeating Characters
- LeetCode #003 Longest Substring Without Repeating Characters
- LeetCode 003 Longest Substring Without Repeating Characters
- 003 Longest Substring Without Repeating Characters [Leetcode]
- 003 - Longest Substring Without Repeating Characters
- log4j
- 使用zxing生成二维码
- ShopStore项目总结(二)
- 熵编码之指数哥伦布编码
- 什么叫人生规划
- 003_LeetCode_3 Longest Substring Without Repeating Characters 题解
- Java 枚举的简单使用
- 算法第五周Container With Most Water[Medium]
- 【angular】
- 10.9日计划
- C++ 笔试题目
- unique(去重函数)的简单用法
- 【BS学习】牛腩新闻发布系统——知识点小结
- Android使用Recyclerview实现图片水平自动循环滚动效果