Leetcode3 Longest Substring Without Repeating Characters

阳光穿透心脏的1/2处 2021-10-14 04:58 323阅读 0赞

Given a string, find the length of the longest substring without repeating characters.

Example 1:

Input: “abcabcbb”
Output: 3
Explanation: The answer is “abc”, with the length of 3.
Example 2:

Input: “bbbbb”
Output: 1
Explanation: The answer is “b”, with the length of 1.
Example 3:

Input: “pwwkew”
Output: 3
Explanation: 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.

  1. class Solution {
  2. public int lengthOfLongestSubstring(String s) {
  3. // 使用set进行存储。
  4. Set<Character> set =new HashSet<>();
  5. // 设置 i ,j 为左右指针。
  6. int i=0,j=0,max=0;
  7. while(j<s.length())
  8. {
  9. // 如果没有右指针指向的元素
  10. if(!set.contains(s.charAt(j)))
  11. {
  12. // 把右指针的元素加入。并移动指针。
  13. set.add(s.charAt(j));
  14. j++;
  15. max =Math.max(max,set.size());
  16. }
  17. // 如果有右指针指向的元素 ,把左指针指向的元素删除,并且移动左指针,
  18. // 当下次循环时,如果判断还是有右指针指向的元素,
  19. //会继续把左指针指向的元素删除,并且移动左指针,直到没有。
  20. else
  21. {
  22. set.remove(s.charAt(i));
  23. i++;
  24. }
  25. }
  26. return max;
  27. }
  28. }

发表评论

表情:
评论列表 (有 0 条评论,323人围观)

还没有评论,来说两句吧...

相关阅读