gpt4 book ai didi

java - 查找包含字符串的最短可能子字符串

转载 作者:搜寻专家 更新时间:2023-11-01 01:32:32 25 4
gpt4 key购买 nike

这是最近一次编程面试中提出的问题。

给定一个随机字符串 S 和另一个具有唯一元素的字符串 T,找到 S 的最小连续子字符串,使其包含 T 中的所有元素。说,

S='adobecodebanc' 
T='abc'
Answer='banc'

我想出了一个解决方案,

public static String completeSubstring(String T, String S){

String minSub = T;
StringBuilder sb = new StringBuilder();
for (int i = 0; i <T.length()-1; i++) {
for (int j = i + 1; j <= T.length() ; j++) {
String sub = T.substring(i,j);
if(stringContains(sub, S)){
if(sub.length() < minSub.length()) minSub = sub;
}
}
}
return minSub;

}
private static boolean stringContains(String t, String s){
//if(t.length() <= s.length()) return false;

int[] arr = new int[256];

for (int i = 0; i <t.length() ; i++) {
char c = t.charAt(i);
arr[c -'a'] = 1;
}
boolean found = true;
for (int i = 0; i <s.length() ; i++) {
char c = s.charAt(i);
if(arr[c - 'a'] != 1){
found = false;
break;
}else continue;
}
return found;
}

此算法的复杂度为 O(n3),但自然不是很好。谁能推荐一个更好的算法。

最佳答案

这是 O(N) 的解决方案。

关于 re: complexity 需要注意的重要一点是,每个工作单元都涉及递增 startend,它们不会递减,并且算法会在递增之前停止都走到尽头。

public static String findSubString(String s, String t)
{
//algorithm moves a sliding "current substring" through s
//in this map, we keep track of the number of occurrences of
//each target character there are in the current substring

Map<Character,int[]> counts = new HashMap<>();
for (char c : t.toCharArray())
{
counts.put(c,new int[1]);
}

//how many target characters are missing from the current substring
//current substring is initially empty, so all of them
int missing = counts.size();

//don't waste my time
if (missing<1)
{
return "";
}

//best substring found
int bestStart = -1, bestEnd = -1;

//current substring
int start=0, end=0;
while (end<s.length())
{
//expand the current substring at the end
int[] cnt = counts.get(s.charAt(end++));
if (cnt!=null)
{
if (cnt[0]==0)
{
--missing;
}
cnt[0]+=1;
}
//while the current substring is valid, remove characters
//at the start to see if a shorter substring that ends at the
//same place is also valid
while(start<end && missing<=0)
{
//current substring is valid
if (end-start < bestEnd-bestStart || bestEnd<0)
{
bestStart = start;
bestEnd = end;
}
cnt = counts.get(s.charAt(start++));
if (cnt != null)
{
cnt[0]-=1;
if (cnt[0]==0)
{
++missing;
}
}
}
//current substring is no longer valid. we'll add characters
//at the end until we get another valid one
//note that we don't need to add back any start character that
//we just removed, since we already tried the shortest valid string
//that starts at start-1

}
return(bestStart<=bestEnd ? s.substring(bestStart,bestEnd) : null);
}

关于java - 查找包含字符串的最短可能子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36212767/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com