Java實現-最小子串覆蓋

給定一個字符串source和一個目標字符串target,在字符串source找到包括所有目標字符串字母的子串。

 注意事項

如果在source沒有這樣的子串,返回"",如果有多個這樣的子串,返回起始位置最小的子串。

說明

在答案的子串中的字母在目標字符串中是否需要具有相同的順序?

——不需要。

樣例

給出source = "ADOBECODEBANC"target = "ABC" 滿足要求的解  "BANC"

public class Solution {
    /**
     * @param source: A string
     * @param target: A string
     * @return: A string denote the minimum window
     *          Return "" if there is no such a string
     */
    public String minWindow(String source, String target) {
        // write your code
        if(source.length()<target.length()){
			return "";
		}
		for(int i=target.length();i<=source.length();i++){
			for(int j=0;j+i<=source.length();j++){
				String s=source.substring(j, j+i);
				StringBuffer sb=new StringBuffer(s);
				int count=0;
				for(int k=0;k<target.length();k++){
					if(sb.indexOf(target.charAt(k)+"")!=-1){
						sb.deleteCharAt(sb.indexOf(target.charAt(k)+""));
						count++;
					}else{
						break;
					}
				}
				if(count==target.length()){
					return s;
				}
			}
		}
		return "";
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章