Longest Substring without Repeating Characters

来源:互联网 发布:淘宝400电话 编辑:程序博客网 时间:2024/06/15 15:45

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.


11/1

A typical sliding window problem, very similar to 'Minimum  Substring covering another String" problem.

public class Solution {    public int lengthOfLongestSubstring(String s) {        int[] cnt = new int[256];        int len = s.length();        int start = 0;        int max_len = 0;        for(int i=0; i<len; i++){            char ch = s.charAt(i);            cnt[ch] ++;            while(cnt[ch] > 1){                char chs = s.charAt(start++); //err1: forget about ++                cnt[chs] --;            }                        int l = i-start+1; //err2: len has been used.            max_len = Math.max(l, max_len);        }                return max_len;    }}

time of O(n): scanning through, space of O(1): cnt has a fixed size;

0 0
原创粉丝点击