1639。具有K个不同字符的子串

给定字符串S和整数K.
计算长度为K且包含K个不同字符的子串数

样例

String: "abcabc"
K: 3

Answer: 3
substrings:  ["abc", "bca", "cab"]
String: "abacab"
K: 3

Answer: 2
substrings: ["bac", "cab"]

 注意本题目的测试字符串长度极大,我测试了好多此最后才没有,报空间不足的错误。

 

import java.util.*;
public class Solution {
    /**
     * @param stringIn: The original string.
     * @param K: The length of substrings.
     * @return: return the count of substring of length K and exactly K distinct characters.
     */
    public int KSubstring(String stringIn, int K) {
        // Write your code here
        if(stringIn.length() resultset = new TreeSet<>();
        Set set = new TreeSet<>();
        for(int i=0;i=0;k--){//找到回退的下标
                        if(stringIn.charAt(i+k)==t){
                            i=i+k;
                            break;
                        }
                    }
                    break;//找到下标后退出循环
                }
                else
                    set.add(t);
                if(set.size()>=K){
                    resultset.add(stringIn.substring(i+j-K+1,i+j+1));//去除重复子串
                }
            }
        }
        return resultset.size();
    }
}

 

你可能感兴趣的:(LeetCode)