无重复字符的最长子串 --java记录

在这里插入图片描述
利用hashset, 集合中记录子串。 用时20+

class Solution {
     public static int lengthOfLongestSubstring(String s) {
    	HashSet<Character> set = new HashSet<Character>(); //key 为 字符,value为索引。     
    	char [] cstr = s.toCharArray();
    	int length = 0 ;
    	int maxlength = 0;
    	int start = 0;   //记录map中子字符串开始的第一个位子
    	int end = 0;	//子字符串末尾位子
    	while(end < s.length()) {
    		if(set.contains(cstr[end])){  //若字符重复,则删除第一个重复字符以及之前的字符串。 abcbdfg  。 将 第一个b 以及之前的字符删除。
    			set.remove(cstr[start]); 
    			start ++;        
    			length -- ;     //每删除一个,长度-1          
    			   
    		}else {
    			set.add(cstr[end]);
    			end ++ ;
    			length ++ ;
    			if(maxlength < length) {
    				maxlength = length;
    			}
    		}
    	}
    	 
        return maxlength;
    }
}

用链表效率高一些,list记录子串。遇到重复子串则将 它与之前删除。 用时10+

class Solution {
     public static int lengthOfLongestSubstring(String s) {
    	LinkedList <Character > list = new LinkedList<Character>();
    	int length = 0;
    	int maxlength = 0;
    	char [] cstr = s.toCharArray();
    	for(int i = 0 ;i < cstr.length; i++) {
    		char str = cstr[i];
    		if(!list.contains(str)) {
    			list.add(str);
    			length ++ ;
    		}else {
    			int temp = list.indexOf(str);  //拿到第一次出现str的索引
    			for( int j = 0 ; j <= temp; j++) { //将它与之前字符删除
    				list.remove();
    			}
    			list.add(str);
    			length = list.size(); 
    		}
    		maxlength = (maxlength > length) ? maxlength:length;
    		
    	}
    	return maxlength;
    	 
    }
    
 
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值