• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
neverlandly
博客园    首页    新随笔    联系   管理    订阅  订阅

G面经Prepare: Search word delete sequence in dictionary

给一个单词一个字典,每次删除单词里任一个字母直到剩下一个字母,形成一个序列,比如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 }

 

posted @ 2016-01-13 09:56  neverlandly  阅读(289)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3