码迷,mamicode.com
首页 > 其他好文 > 详细

Longest Substring Without Repeating Characters

时间:2016-12-04 00:13:41      阅读:187      评论:0      收藏:0      [点我收藏+]

标签:without   语句   处理   重复   长度   find   i++   pre   strong   

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

Examples:

Given "abcabcbb", the answer is "abc", which the length is 3.

Given "bbbbb", the answer is "b", with the length of 1.

Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring.

我的思路:

首先是设置了start和i两个变量,其中start用于指示当前子串首的前一个字符的位置,i表示当前子串尾字符的位置。数组posflag用于记录出现过的重复字符的当前最新位置(忽略当前字符,也就是当前字符上次出现的位置)。主要分支有两部分,第一部分是当前字符非重复字符,此时应该将该字符放入posflag以更新,另外需要记录此时合法子串的长度是否比记录的最长子串长,并进行更新操作;第二部分是出现重复字符时的处理,此时应该将start的位置移至重复字符上次出现的位置(但是需要注意的是:start只能向后移动,不能向前移动,这个易证,所以在这里会有斜线部分的判断语句),然后更新字符出现位置,并且比较当前子串长度是否大于记录的最大子串长以便做相应的更新。代码如下

public class Solution {
    public int lengthOfLongestSubstring(String s) {
    	int[] posflag = new int[256];
    	for(int i = 0;i < 256; i++)
    		posflag[i] = -1;
    	int start = -1,max = 0;
    	for(int i = 0;i < s.length(); i++){
    		//System.out.println((int)s.charAt(i));    		
    		if(posflag[(int)s.charAt(i)]!=-1){
    			if(posflag[(int)s.charAt(i)]>start)
    				start = posflag[(int)s.charAt(i)];
    			posflag[(int)s.charAt(i)] = i;
    			if(i-start>max)
    				max = i-start;
    		}else{
    			
    			posflag[(int)s.charAt(i)] = i;
    			if(i-start>max)
    				max = i-start;
    		}
    	}
    	//System.out.println(max);
    	return max;
    }
}

  

Longest Substring Without Repeating Characters

标签:without   语句   处理   重复   长度   find   i++   pre   strong   

原文地址:http://www.cnblogs.com/lxk2010012997/p/6129826.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!