Leetcode-Longest Substring Without Repeating Characters
来源:互联网 发布:惠普电池检测软件 编辑:程序博客网 时间:2024/06/11 21:32
题目:
给定一个字符串,找到一个最长的子串,使其不包含重复的字符。最直观的方法则是依次以每个字符开头进行查找,记录下以各个字符为起始位置的最长子串,最后输出最大的长度,但是该方法算法复杂度为O(n^2),不是理想的解法。
class Solution { public int lengthOfLongestSubstring(String s) { if(s==null||s.length()==0) return 0; int res = 1; for(int i = 0;i<s.length();i++) { HashSet<Character> temp = new HashSet<>(); temp.add(s.charAt(i)); for(int j = i+1;j<s.length();j++) { if(!temp.contains(s.charAt(j))) { temp.add(s.charAt(j)); res++; } else { break; } } if(temp.size()>res) { res = temp.size(); } } return res; }}
该题的解法比较巧妙,利用一个滑动窗口来维护一个最长子串,首先用一个标签作为窗口起始位置,用一个标签作为窗口的右边界位置。用一个hashMap来维护子串,若hashMap里没有当前的字符则右边界右移并更新当前子串的长度。若hashMap存在当前字符,则找到重复字符的位置,这个地方需要注意的是,窗口新的左边界应该是当前左边界和重复位置中取较大的一个,因为hashMap没有将以前的字符删除,所以可能会使重复位置在当前左边界的左边。
class Solution { public int lengthOfLongestSubstring(String s) { if(s==null) return 0; HashMap<Character, Integer> map = new HashMap<>();int i = 0,ans = 0;for(int j = 0;j<s.length();j++){if(map.containsKey(s.charAt(j))){i = Math.max(map.get(s.charAt(j)),i); //更新左边界,取当前左边界和重复字符位置中的较大值}ans = Math.max(ans, j-i+1); //更新子串的长度map.put(s.charAt(j), j+1);}return ans; }}
阅读全文
0 0
- 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
- leetcode之Longest Substring Without Repeating Characters
- 4.3常用对象API-集合框架(Collection,Map,泛型,集合工具类)
- 课堂笔记-文本挖掘-CM1
- tensorflow 加载minist数据
- C#读取与修改XML文档
- GPS数据读取与处理
- Leetcode-Longest Substring Without Repeating Characters
- js获得input中的value值
- 《游戏设计的100个原理》摘要
- java单例模式
- HDU 4035 Maze(数学期望)
- Java中有关null的9件事
- SuperAgent使用简介
- 《Linux进程、线程和调度》4次课程高清ppt和录播链接
- 既然时间是相对的,那当我们谈论宇宙年龄时我们在谈论什么?