leetcode第三题Longest Substring Without Repeating Characters java

Longest Substring Without Repeating Characters

 

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.

采用的是比较笨的遍历方法,time=380ms  可通过,不过还要优化

public class Solution {
    public int lengthOfLongestSubstring(String s) {
	        int length=s.length();
	        int max=0,index=0,count=1;
	        
	        while(index<length){
	        	if(index+count>=length){
		             if(max<=count){
		                  max=count;
		                  count=1;
		             }
		             break;		                
		        }
	            for(int i=index;i<index+count;i++){	            	
	                if(s.charAt(index+count)==s.charAt(i)){
	                    index=i+1;
	                    if(max<=count){
	                        max=count;
	                    }
	                    count=0;
	                    break;
	                }
	            }
	            count++;
	        }
	        return max;
	        
	    }
}


posted @ 2015-03-10 14:18  懒人部落  阅读(156)  评论(0编辑  收藏  举报