首页 > 其他 > 详细

[Leetcode]3. Longest Substring Without Repeating Characters

时间:2021-01-16 22:03:31      阅读:27      评论:0      收藏:0      [点我收藏+]

题目描述

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

  • Example 1:
Input: s = "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.
  • Example 2:
Input: s = "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.
  • Example 3:
Input: s = "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3.
Notice that the answer must be a substring, "pwke" is a subsequence and not a substring.
  • Example 4:
Input: s = ""
Output: 0

给定一个字符串,求最长不重复子串,本题主要考查滑动窗口和哈希表。

代码实现

import java.util.HashMap;
import java.util.Map;

class Solution {

  public int lengthOfLongestSubstring(String s) {
    int left = 0;
    int right = 0;
    //滑动窗口区间[left,right]
    int maxLen = 0;
    Map<Character, Integer> map = new HashMap<>();
    while (right < s.length()) {
      char c = s.charAt(right);
      if (map.containsKey(c)) {
        left = Math.max(left, map.get(c) + 1);
      }
      map.put(c, right);
      maxLen = Math.max(maxLen, right - left + 1);
      right++;
    }
    return maxLen;
  }

  public static void main(String[] args) {
    System.out.println(new Solution().lengthOfLongestSubstring("abcabcdbb"));
    System.out.println(new Solution().lengthOfLongestSubstring("bbbbb"));
    System.out.println(new Solution().lengthOfLongestSubstring("b"));
  }
}

[Leetcode]3. Longest Substring Without Repeating Characters

原文:https://www.cnblogs.com/strongmore/p/14287041.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!