Longest Substring Without Repeating Characters

来源:互联网 发布:数据精灵ios破解版 编辑:程序博客网 时间:2024/05/12 00:09

原题:

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 int lengthOfLongestSubstring(String s) {if(s==null || s.isEmpty()) {return 0;}if(s.length()==1) {return 1;}boolean[] flags = new boolean[256];int maxLen = 1;int slow = 0;int fast = 0;while(fast<s.length()) {if(flags[s.charAt(fast)]) {while(s.charAt(slow)!=s.charAt(fast)) {flags[s.charAt(slow)] = false;slow++;}slow++;fast++;} else {flags[s.charAt(fast)] = true;fast++;maxLen = Math.max(maxLen, fast-slow);}}return maxLen;    }


0 0
原创粉丝点击