栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

代码以查找对所有输入均无效的最长的带有唯一K字符的子字符串

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

代码以查找对所有输入均无效的最长的带有唯一K字符的子字符串

您的实现无法按预期方式运行,因为原始的python解决方案存在错误。我对您的代码做了一些修改。希望现在还好:

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<Character> 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<len){ if (count==k && j -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<len){     if (unique.add(inputArr[j])){         count++;     }     j++; } else {         if (unique.remove(inputArr[i])){         // 3. remove all consecutive chars of the same value         char c = inputArr[i];  // save as temp char         while (inputArr[i] == c)         {  i++;         }         count--;         }      }        }         return input.substring(maxStartIndex,maxEndIndex);    }}

现在的输出是:

deeeeggeeeegg


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/516422.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号