Google算法题:最多有k个不同字符的最长子字符串

题目

题目来源:Link

Google算法题:最多有k个不同字符的最长子字符串_第1张图片


分析


Google算法题:最多有k个不同字符的最长子字符串_第2张图片


代码


从O(n^3)到O(n^2)到O(n)逐步优化

package com.graph;

import java.util.*;

import org.omg.CORBA.INTERNAL;

public class Solution {
	//TC=O(n^3)
	public int solve(String str, int k){
		//special case
		if(str==null || str.length()==0) return 0;
		if(k==0) return 0;
		
		//normal case
		int n = str.length();
		int[][] f = new int[n][n];
		//init f
		for(int i=0; ilen?max:len;
				}
			}
		}	
		
		return max;
	}
	//优化代码
	//TC=O(n)
	public int solve_op(String str, int k) {
		//special case
		if(str==null || str.length()==0) return 0;
		if(k==0) return 0;
		
		//normal case
		int n = str.length();
		int max=0;
		int i=0,j=0;
		Map map = new HashMap();
		for(; i1) {
					map.put(c, map.get(c)-1);
				}else {
					map.remove(c);
				}
			}
		}		
		
		return max;
	}
	
	public static void main(String[] args) {
		Solution s = new Solution();
		System.out.println("solve:"+s.solve("ecebaaaa",3));
		System.out.println("solve_op:"+s.solve_op("ecebaaaa",3));
	}
}


你可能感兴趣的:(Google,双指针)