zoukankan      html  css  js  c++  java
  • [Algo] 99. Dictionary Word I

    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;
      }
    }
  • 相关阅读:
    android 之 ListView相关
    android 之 菜单
    android 之 Dialog
    android 之 View
    android 之 service
    android 之 Intent、broadcast
    Service Broadcast简单音乐播放功能
    剑指offer面试题43:n个筛子的点数
    C# LINQ语法
    C# Linq
  • 原文地址:https://www.cnblogs.com/xuanlu/p/13123564.html
Copyright © 2011-2022 走看看