首页 > 代码库 > [LeetCode]3 Longest Substring Without Repeating Characters
[LeetCode]3 Longest Substring Without Repeating Characters
https://oj.leetcode.com/problems/longest-substring-without-repeating-characters/
http://fisherlei.blogspot.com/2012/12/leetcode-longest-substring-without.html
public class Solution { public int lengthOfLongestSubstring(String s) { if (s == null || s.isEmpty()) return 0; // invalid input // A map of [char, position] Map<Character, Integer> map = new HashMap<>(); char[] chars = s.toCharArray(); int len = chars.length; int start = 0; int end = 0; int maxLen = -1; for (; end < len ; end ++) { char c = chars[end]; Integer lastPos = map.get(c); if (lastPos == null) { map.put(c, end); int curLen = end - start + 1; if (curLen > maxLen) maxLen = curLen; } else { // Clear all chars <= lastPos, including c. // Then update c with end. // reset start = lastPos + 1; for (int i = start ; i <= lastPos ; i ++) { map.remove(chars[i]); } start = lastPos + 1; map.put(c, end); } } if (maxLen == -1) // All chars are the same. return 1. return 1; return maxLen; } }
[LeetCode]3 Longest Substring Without Repeating Characters
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。