code to find longest substring with unique K characters not working for all inputs

后端 未结 1 724
面向向阳花
面向向阳花 2021-01-27 06:49

Given a String, \"\"aabbcdeeeeggi\" and k=3, the code should find longest substring with maximum of k unique characters. For the above input, it should be \"deeeeggi\".

1条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-27 07:11

    Your implementation does not work the way as expected, is because the original python solution has bug. I made some modifications to your code. Hope it's now all right:

    public class SubStringWithKUniqueCharacters {
    
        public static void main(String[] args){
    
            System.out.println(longestSubStringWithUniqueK("aabbcdeeeeggi", 3));
            System.out.println(longestSubStringWithUniqueK("aabbcdeeeeggi", 2));
        }
    
        public static String longestSubStringWithUniqueK(String input, int k){
            int len = input.length();
            Set unique = new HashSet<>();
    
            int i = 0;
            int j = 0;
            int count = 0;
            int maxStartIndex = 0;
            int maxEndIndex  = 0;
            int maxLen = 0;
            char[] inputArr = input.toCharArray();
    
            while (i maxLen){
                    maxStartIndex = i;
                    maxEndIndex = j;
                    maxLen = maxEndIndex - maxStartIndex;
                }
                // 1. if we reach the end of the string, we're done.
                if (j + 1 > len){
                    break;
                }
                // 2. changed to count <= k here
                else if (count<= k && j

    The output now is:

    deeeegg
    eeeegg
    

    0 讨论(0)
提交回复
热议问题