给一个单词一个字典,每次删除单词里任一个字母直到剩下一个字母,形成一个序列,比如office->offce->ofce->ofc->oc->c。问是否字典里存在一个这种序列
1 package checkDictExistSequence; 2 import java.util.*; 3 4 public class Solution { 5 HashSet<String> dict = new HashSet<String>(); 6 7 public String check(String[] arr, String word) { 8 for (String str : arr) 9 dict.add(str); 10 if (checkSeq(new StringBuffer(word))) return "true"; 11 return "false"; 12 } 13 14 public boolean checkSeq(StringBuffer sb) { 15 if (sb.length() == 1) return true; 16 for (int i=0; i<=sb.length()-1; i++) { 17 char cur = sb.charAt(i); 18 sb.deleteCharAt(i); 19 if (dict.contains(sb.toString())) { 20 if (checkSeq(sb)) return true; 21 } 22 sb.insert(i, cur); 23 } 24 return false; 25 } 26 27 28 /** 29 * @param args 30 */ 31 public static void main(String[] args) { 32 // TODO Auto-generated method stub 33 Solution sol = new Solution(); 34 System.out.println(sol.check(new String[]{"offce", "ofce", "ofc", "oc", "c"}, "office")); 35 } 36 37 }
时间: 2024-10-28 11:47:19