首页 > 其他 > 详细

[Algo] 99. Dictionary Word I

时间:2020-06-14 10:15:06      阅读:39      评论:0      收藏:0      [点我收藏+]

Given a word and a dictionary, determine if it can be composed by concatenating words from the given dictionary.

Assumptions

  • The given word is not null and is not empty
  • The given dictionary is not null and is not empty and all the words in the dictionary are not null or empty

Examples

Dictionary: {“bob”, “cat”, “rob”}

  • Word: “robob” return false

  • Word: “robcatbob” return true since it can be composed by "rob", "cat", "bob"

public class Solution {
  public boolean canBreak(String input, String[] dict) {
    Set<String> set = new HashSet<>(Arrays.asList(dict));
    return helper(input, set, 0);
  }

  private boolean helper(String input, Set<String> set, int index) {
    if (index == input.length()) {
      return true;
    }
    for (int i = index; i < input.length(); i++) {
      // substring need to be i + 1
      if (set.contains(input.substring(index, i + 1)) && helper(input, set, i + 1)) {
        return true;
      }
    }
    return false;
  }
}

 

[Algo] 99. Dictionary Word I

原文:https://www.cnblogs.com/xuanlu/p/13123564.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!