【Java】面试题48:最长不含重复字符的子字符串

题目:最长不含重复字符的子字符串

请从字符串中找出一个最长的不包含重复字符的子字符串,计算该最长子字符串的长度。假设字符串中只包含从’a’到’z’的字符。例如,在字符串中”arabcacfr”,最长非重复子字符串为”acfr”,长度为4。

**主要思路:**使用动态规划,记录当前字符之前的最长非重复子字符串长度f(i-1),其中i为当前字符的位置。每次遍历当前字符时,分两种情况:

1)若当前字符第一次出现,则最长非重复子字符串长度f(i) = f(i-1)+1。
2)若当前字符不是第一次出现,则首先计算当前字符与它上次出现位置之间的距离d。若d大于f(i-1),即说明前一个非重复子字符串中没有包含当前字符,则可以添加当前字符到前一个非重复子字符串中,所以,f(i) = f(i-1)+1。若d小于或等于f(i-1),即说明前一个非重复子字符串中已经包含当前字符,则不可以添加当前字符,所以,f(i) = d。

**关键点:**动态规划,两个重复字符的距离

**时间复杂度:**O(n)

方法一:

	public static int longestSubstringWithoutDuplication(String str) {
		if(str==null || str.equals(""))
			return 0;
		
		int maxLength=0;
		int curLength=0;
		int[] position = new int[26];
		for(int i=0;i<position.length;i++) {
			position[i]=-1; //初始化为-1,负数表示没出现过
		}
		
		for(int i=0;i<str.length();i++) {
			int prevIndex = position[str.charAt(i)-'a']; 
			int distance=i-prevIndex;
			
			//如果当前字符没有出现过,或者出现后的d大于当前最长字串长度
			if(prevIndex<0 || distance>curLength)
				curLength++;
			else { //如果d<=当前最长字串长度,说明两个相同字符在最长字串中
				if(curLength > maxLength)
					maxLength = curLength;
				
				curLength = distance;	
			}
			position[str.charAt(i)-'a'] = i; //更新当前字符出现的位置
		}
		
		if(curLength>maxLength)
			maxLength=curLength;
		
		return maxLength;
	}

方法二:使用ArrayList

package jianZhiOffer;

import java.util.ArrayList;
import java.util.List;

public class Demo4801 {

	public static void main(String[] args) {
		System.out.println(lengthOfLongestSubstring("arabcacfr"));
	}
	
	
	public static int lengthOfLongestSubstring(String str) {
		if(str.length()==0)
			return 0;
		
		int maxLength=1;
		List<Character> list = new ArrayList<Character>();
		list.add(str.charAt(0));
		for(int i=1;i<str.length();i++) {
			if(list.contains(str.charAt(i))) {
				//返回与当前字符相同字符的索引
				int index = list.indexOf(str.charAt(i)); 
				list = list.subList(index+1, list.size());
				list.add(str.charAt(i));
				maxLength = Math.max(maxLength, list.size());
			}else {
				list.add(str.charAt(i));
				maxLength = Math.max(maxLength, list.size());
			}
		}
		return maxLength;
	}

}

猜你喜欢

转载自blog.csdn.net/weixin_38361153/article/details/88925999