[leetcode]3. Longest Substring Without Repeating Characters
来源:互联网 发布:婚礼效果图软件 编辑:程序博客网 时间:2024/05/03 19:57
题目大意:
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.
Subscribe to see which companies asked this question.
分析:
1.HashMap: key -> string s charAt之后的每一个字母
value -> 每一个字母的索引
2.没有重复字母出现时,max是i+1-position,此时的position=0,其实max就是i+1,而是当前遍历的字母的索引,所以i+1就是当前substring的长度;
出现重复的时候,i+1-position表达就是两次重复出现的间隔,例如"abcabcbb",就是两个a的间隔是3
3.当有重复出现时,position的值才进行更新,position=Math.max(position, map.get(cha)+1);
之后的map.put(cha, i), i则是重复的字母的重复出现位置的索引;
有了这样的基础,再进行i+1-position的更新。
4.position的值更新时,不可以position=Math.max(position, map.get(cha)),因为若string=“a”,只有一个字母的情况下结果输出0,显然不对
public static int lengthOfLongestSubstring(String s) {Map<Character,Integer> map=new HashMap<>();int max=0;int position=0;for(int i=0;i<s.length();i++){char cha=s.charAt(i);if(map.containsKey(cha)){position=Math.max(position, map.get(cha)+1);}map.put(cha, i);max=Math.max(max, i+1-position);}return max; }
- [LeetCode]3.Longest Substring Without Repeating Characters
- LeetCode 3.Longest Substring Without Repeating Characters
- LeetCode --- 3. Longest Substring Without Repeating Characters
- [Leetcode] 3. Longest Substring Without Repeating Characters
- [leetcode] 3.Longest Substring Without Repeating Characters
- [leetcode] 3. Longest Substring Without Repeating Characters
- [Leetcode]3. Longest Substring Without Repeating Characters
- leetcode 3. Longest Substring Without Repeating Characters
- 【Leetcode】3. Longest Substring Without Repeating Characters
- leetcode 3. Longest Substring Without Repeating Characters
- LeetCode-3.Longest Substring Without Repeating Characters
- LeetCode 3.Longest Substring Without Repeating Characters
- LeetCode - 3.Longest Substring Without Repeating Characters
- Leetcode 3. Longest Substring Without Repeating Characters
- 3. Longest Substring Without Repeating Characters LeetCode
- (Leetcode)3. Longest Substring Without Repeating Characters
- leetcode 3. Longest Substring Without Repeating Characters
- LeetCode-3. Longest Substring Without Repeating Characters
- Python脚本:MySQL表写入MongoDB
- leetcode解题之226# Invert Binary Tree Java版 (交换树的左右子树)
- MySQL数据库在单机生产环境下配置注意事项
- ORA-01503: CREATE CONTROLFILE failed
- 名企面试题个人总结——蘑菇街2017校园招聘(特殊交换)
- [leetcode]3. Longest Substring Without Repeating Characters
- Project Euler Problem 5: Smallest multiple
- MySQL 查询所有表中的记录数
- bzoj 1638 dfs
- struts2升级到2.3.32版本,防止漏洞编号S2-045,CVE编号:cve-2017-5638
- 4489: misaka and last order(思路)
- Java Files & Stream
- ModBus协议-功能码第0节
- 博客搬家了