Leetcode-longest-substring-without-repeating-characters
来源:互联网 发布:win10怎么样卸载软件 编辑:程序博客网 时间:2024/06/01 10:18
题目描述
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.
题目非常好懂,但是问题不是 很好解决。
采用一个滑动窗口的方法,string从前向后遍历,用一个hashmap保存所有的字符和位置,每次遍历都会在hashmap中寻找存不存在,不存在,则窗口宽度加1,如果存在,窗口截取上一个该字符出现的位置到当前出现的位置。这样下来,最后返回的max就是我们想要的答案。
import java.util.*;public class Solution { public int lengthOfLongestSubstring(String s) { if(s == null || s.length() == 0) return 0; HashMap<Character, Integer> map = new HashMap<Character, Integer>(); int window = 0; int max = 0; for(int i=0; i<s.length(); i++) { char c = s.charAt(i); window = Math.max(window, map.containsKey(c) ? (map.get(c)+1) : 0); max = Math.max(max, i- window +1); map.put(c, i); } return max; }}
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
- Python学习笔记——模块
- poj 3928
- 超车
- CABAC 基础二-算术编码
- Iterator 迭代器模式--隐藏访问
- Leetcode-longest-substring-without-repeating-characters
- 用cmd命令连接MySQL数据库遇到的问题
- zynq学习04 zynq中PS通过MIO控制LED
- 要么读书,要么健身,要么恋爱(二)追风筝的人
- 网络基础概念(一)
- 【华为】Redis客户端API使用(java)
- 两个月了
- Keep 移动健身专家
- 和尚头上应该点几个点?