[Leetcode #3]Longest Substring Without Repeating Characters 无重复字符的最长子串
来源:互联网 发布:c语言谭浩强第三版答案 编辑:程序博客网 时间:2024/05/20 07:36
原题地址:https://leetcode.com/problems/longest-substring-without-repeating-characters/
题目要求是:给定一个字符串,找出其中无重复字符的最长子串的长度。例如:
“abcabcbb”,无重复字符最长子串是“abc”,返回长度3
“bbbbb”,无重复字符最长子串是“b”,返回长度1
"pwwkew",无重复字符最长子串是“wke”,返回长度3
这类问题,要减小计算量,一般采用“滑动窗口法”。所谓滑动窗口,也就是先固定左端,右端向右滑动,窗口扩大。如果出现了不符合条件的情况,再把左端向右滑动,窗口缩小。当滑动到最右端以后,迭代结束,找出滑动过程中出现的峰值即可。
举个比较直观的例子:"abcbadbb"
假设窗口左端winL目前位于'c',窗口右端winR目前位于'd'。在遍历过程中,把所有出现过的字符放到一个map中,并记录它的后面一个位置。比如现在这个情况,map.get('b')就会指向4这个位置。winR向右滑动一步到字符'b',此时发现map中已经存在该字符了,不符合“无重复字符”这个条件,需要滑动winL。winL该滑动到哪里呢?如果仅仅是向右滑动一步到'b',还是有重复字符。其实从图上就能很容易看出,应该滑动之前出现过的字符'b'的后面一个位置,也就是之前我们在map中记录的那个位置。
当然,在每一次滑动过程中都需要记录子串的长度,最终返回最长的无重复字符子串的长度。
具体代码实现:
public class Solution { public int lengthOfLongestSubstring(String s) { int len = s.length(); int maxLen = 0; Map<Character, Integer> map = new HashMap<>(); for (int winL = 0, winR = 0; winR < len; winR++) { if (map.containsKey(s.charAt(winR))) { winL = Math.max(map.get(s.charAt(winR)), winL); } maxLen = Math.max(maxLen, winR - winL + 1); map.put(s.charAt(winR), winR + 1); } return maxLen; }}
0 0
- [Leetcode #3]Longest Substring Without Repeating Characters 无重复字符的最长子串
- LeetCode-3:Longest Substring Without Repeating Characters (最长无重复字符的子串) --medium
- leetcode:Longest Substring Without Repeating Characters (寻找最长无重复字符的子串)
- Longest Substring Without Repeating Characters (返回最长无字符重复的子串长度)
- Longest Substring Without Repeating Characters (最长无重复字符的子串)
- [Lintcode] Longest Substring Without Repeating Characters 最长无重复字符的子串
- 384.Longest Substring Without Repeating Characters-最长无重复字符的子串(中等题)
- 字符的最长无重复子串长度Longest Substring Without Repeating Characters
- LeetCode OJ 之 Longest Substring Without Repeating Characters (无重复的最长子串)
- LeetCode-3 Longest Substring Without Repeating Characters(最长无重复子串)
- leetcode 3 : Longest Substring Without Repeating Characters 最长无重复子串 (C# 语言版)
- leetcode 3 Longest Substring Without Repeating Characters最长无重复子串
- LeetCode 3. Longest Substring Without Repeating Characters--不包含重复字符的最长子串长度
- 3. Longest Substring Without Repeating Characters 无重复字符的最长子字符串
- 寻找最长无重复字符子串 Longest Substring Without Repeating Characters
- Longest Substring Without Repeating Characters,最长无重复字符子串
- 【LeetCode】4. Longest Substring Without Repeating Characters 最长无重复子串
- LeetCode OJ-3.Longest Substring Without Repeating Characters(最长无重复子串)
- Android屏幕知识点
- pat_BL_1001
- Mysql中主从复制的原理、配置过程以及实际案例
- RelativeLayout相对布局
- 14. Longest Common Prefix
- [Leetcode #3]Longest Substring Without Repeating Characters 无重复字符的最长子串
- H5总结
- Vijos P1334 NASA的食物计划(动态规划,二维费用的01背包)
- 华为2017上机题(北京优招)
- JMS和ActiveMQ
- java中Class.forName的含义
- JAVA中的集合框架
- 树的上课笔记
- BufferedInputStream。。。。。。。BufferedReader和BufferedWriter