gpt4 book ai didi

java - 数组中最后一个和第一个字符匹配的最长序列

转载 作者:太空宇宙 更新时间:2023-11-04 13:30:25 25 4
gpt4 key购买 nike

最近有人问我一个问题,即从字符串数组创建一个序列,以便如果元素 1 的最后一个字符与元素 2 的第一个字符匹配,则字符串元素可以组合。

例如:{"ab", "bc", "cd", "ad", "def", "cedd"} 应返回“abceddef”。

我从上述输入中得到的是“abcdef”。

public class LongestSubstringConsecutiveEnds {

static StringBuilder sbMax = new StringBuilder();
static StringBuilder sbTemp;

public static void main(String[] args) {

String[] inputStrings = {"ab", "bc", "cd", "ad", "def", "cedd"};
List<String> inputList = new ArrayList<String>(Arrays.asList(inputStrings));

for(int i=0; i<inputList.size(); i++) {

String str = inputList.get(i);
sbTemp = new StringBuilder(str);
inputList.remove(str);
longestSequence(sbTemp, new ArrayList<String>(inputList));
inputList.add(0, str);
}

System.out.println(sbMax.toString());
}

private static void longestSequence(StringBuilder tempSubstring, final List<String> inputList) {

System.out.println(tempSubstring.toString() + inputList);
if(tempSubstring.length() > sbMax.length()) {
sbMax.delete(0, sbMax.length());
sbMax.append(tempSubstring);
}

for(int i=0; i<inputList.size(); i++) {

String inputListString = inputList.get(i);
char tempStrLastChar = tempSubstring.charAt(tempSubstring.length()-1);
if(inputListString.charAt(0) == tempStrLastChar) {

String str = inputList.remove(i);
longestSequence(tempSubstring.append(inputListString.substring(1)), inputList);
inputList.add(i, str);
}
}
}
}

最佳答案

根据你的问题:

if the last character of element 1 matches the first character of element 2.

您在问题中描述的部分可以很容易完成:

for (int i = 0; i < strings.length - 1; i++) {
// last char of element i is equal first char of element i+1
if (strings[i].charAt(strings[i].length()-1) == strings[i+1].charAt(0)) {
// print element i.
System.out.print(strings[i]);
}
}

输出:

cd

即,位置 3 与 4 匹配 (cd-def)

但这不匹配

should return "abceddef" And I can't find a logic... where last ef comes from? you mean match when for example last is a and first is b ??. That would be:

for (int i = 0; i < strings.length - 1; i++) {
// get last and first char
String actual = strings[i];
char last = actual.charAt(actual.length()-1);
char first = strings[i+1].charAt(0);

if ((int) first == last + 1) {
System.out.print(actual);
}
}

输出:

ab

即位置 2 与 3 匹配 (ab-cd)

关于java - 数组中最后一个和第一个字符匹配的最长序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32251313/

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