Leetcode: Longest Substring Without Repeating Characters

来源:互联网 发布:取消数据流量套餐 编辑:程序博客网 时间:2024/06/10 04:07

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.


public class Solution {    public int lengthOfLongestSubstring(String s) {        if (s == null || s.length() == 0) {            return 0;        }                Set<Character> set = new HashSet<Character>();        int max = 1;        int start = 0;        int end = 0;                while (end < s.length()) {            if (set.contains(s.charAt(end))) {                max = Math.max(max, end - start);                while (s.charAt(start) != s.charAt(end)) {                    set.remove(s.charAt(start));                    start++;                }                start++;            } else {                set.add(s.charAt(end));            }            end++;        }                return Math.max(max, end - start);    }}


0 0