leetcode : Longest Substring Without Repeating Characters 解题报告
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
tag : two pointers HashSet
思路:
(1)从第一个字符开始遍历,计算以每个字符开始的最长无重复子字符串。
(2)每一计算的子串存在零时的HashSet里面。 注意HashSet这个数据结构, 增加元素是add()不是put().
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | public class Solution { public int lengthOfLongestSubstring(String s) { if (s == null || s.length() == 0 ) { return 0 ; } int max = 0 ; for ( int i = 0 ; i < s.length(); i++) { HashSet<Character> set = new HashSet<Character>(); set.add(s.charAt(i)); if (max >= s.length() - i) { break ; } for ( int j = i + 1 ; j < s.length(); j++) { if (set.contains(s.charAt(j))) { break ; } else { set.add(s.charAt(j)); } } max = Math.max(max, set.size()); } return max; } } |
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步