You need to enable JavaScript to run this app. 判断字符串列表能否拼接为指定单词的算法实现问题
优惠活动
大模型
产品
解决方案
定价
更多

判断字符串列表能否拼接为指定单词的算法实现问题

字符串列表拼接校验规则

我们需要实现的校验逻辑为:判断给定的字符串列表是否可以拼接得到指定的目标单词,列表中的每个元素最多可使用1次,也可以选择不使用。

测试用例

  • 测试用例1
    • 输入:目标单词word = foobarbaz,字符串列表内容为:foob、foo、ba、ba、r、z
    • 输出:true

  • 测试用例2
    • 输入:目标单词word = foobarbaz,字符串列表内容为:foo、fooz、ba、r、z
    • 输出:false

约束条件

可假设目标单词长度≥1,字符串列表的元素个数≥1。

Java实现代码说明

你提供的原始代码存在两处可优化的问题:

  1. 递归逻辑中未移除已使用的字符串元素,会导致同一个元素被重复拼接,不符合「每个元素最多使用1次」的规则
  2. 测试用例1的初始数据少添加了一个ba元素,运行无法得到正确结果

修正后可正常运行的代码如下:

import java.util.ArrayList;

public class TilePossibilties {
    public static void main(String[] args) {
        String word = "foobarbaz";
        ArrayList<String> arrayList = new ArrayList<>();
        arrayList.add("foob");
        arrayList.add("foo");
        arrayList.add("ba");
        arrayList.add("ba");
        arrayList.add("r");
        arrayList.add("z");
        System.out.println(check(word, arrayList));
    }

    private static boolean check(String word,ArrayList<String> arrayList) {
        // 拷贝原始列表避免修改原数据
        return isOkay(new ArrayList<>(arrayList), word, "");
    }

    private static boolean isOkay(ArrayList<String> remainList, String word, String candidate) {
        for(int i = 0; i < remainList.size(); i++){
            String test = candidate + remainList.get(i);
            if(test.equals(word)) {
                return true;
            }
            if(word.startsWith(test)) {
                // 移除当前已使用的元素,传入下一层递归
                ArrayList<String> nextList = new ArrayList<>(remainList);
                nextList.remove(i);
                boolean tempResult = isOkay(nextList, word, test);
                if(tempResult) {
                    return true;
                }
            }
        }
        return false;
    }
}

内容的提问来源于stack exchange,提问作者mortalcoding

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.15 13:45:03