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

时间:2015-08-27 13:54:17

标签: java arrays

我最近被问到一个问题是从字符串数组创建一个序列,这样如果元素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);
            }
        }
    }
}

2 个答案:

答案 0 :(得分:0)

根据你的问题:

  

如果元素1的最后一个字符与元素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匹配(c d - d ef)

但这与

不符
  

应该返回&#34; abceddef&#34;   我无法找到一个逻辑......最后 ef 来自哪里?你的意思是匹配,例如last是 a ,首先是 b ??那将是:

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匹配( b - c d)

答案 1 :(得分:0)

public static void main(String...args){
    final String[] input={"ab", "bc", "cd", "ad", "def", "cedd"};
    System.out.println( funkyConcat(input));
}
private static String funkyConcat(String...strings){
    String ret="";
    for(String i:strings){
        if(ret.isEmpty()){
            ret=i;
        }else if(ret.substring(ret.length()-1).equals(i.substring(0,1))){
            ret+=i.substring(1);
        }
    }
    return ret;
}