Leetcode-longest-substring-without-repeating-characters

来源:互联网 发布:win10怎么样卸载软件 编辑:程序博客网 时间:2024/06/01 10:18

题目描述


Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.

题目非常好懂,但是问题不是 很好解决。

采用一个滑动窗口的方法,string从前向后遍历,用一个hashmap保存所有的字符和位置,每次遍历都会在hashmap中寻找存不存在,不存在,则窗口宽度加1,如果存在,窗口截取上一个该字符出现的位置到当前出现的位置。这样下来,最后返回的max就是我们想要的答案。

import java.util.*;public class Solution {    public int lengthOfLongestSubstring(String s) {        if(s == null || s.length() == 0)            return 0;        HashMap<Character, Integer> map = new HashMap<Character, Integer>();        int window = 0;        int max = 0;                for(int i=0; i<s.length(); i++) {            char c = s.charAt(i);            window = Math.max(window, map.containsKey(c) ? (map.get(c)+1) : 0);            max = Math.max(max, i- window +1);            map.put(c, i);        }                return max;    }}


0 0
原创粉丝点击