12
返回列表 发新帖
楼主: wwwyhx
跳转到指定楼层
上一主题 下一主题
收起左侧

Google : 句子分割

🔗
 楼主| wwwyhx 2011-7-17 21:21:49 | 只看该作者
全局:
回复  wwwyhx
类似这样:can[ i ]代表从头开始共i个字符能否被分割。内存循环其实可以到maxL也就是字典中单词的最大长度就退出,所以复杂度可以到O(maxL*n)。
darksteel 发表于 2011-7-16 02:53



    很好,谢谢,我那个递归的的确存在大量重复计算
回复

使用道具 举报

🔗
babyfrog 2011-7-19 12:20:18 | 只看该作者
全局:
本帖最后由 babyfrog 于 2011-7-19 12:25 编辑

也贴上我的回朔@@

  1. import java.util.LinkedList;

  2. public class Sentence {
  3.     public static void main(String[] args) {
  4.         String[] dic = {"a", "apply", "back", "i", "is", "isasen", "sentence", "this", "tence"};
  5.         String sentence = "thisisasentence";
  6.         splitSentence(sentence, dic);
  7.     }

  8.     public static void splitSentence(String sentence, String[] dic) {
  9.         int index = 0;
  10.         boolean valid = true;
  11.         StringBuffer buffer = new StringBuffer();
  12.         LinkedList<String> wordstack = new LinkedList<String>();
  13.         LinkedList<Integer> indexstack = new LinkedList<Integer>();
  14.         
  15.         while (true) {
  16.             if (index == sentence.length()) {                    //BACKTRACK
  17.                 if(indexstack.isEmpty()) break;                   //EXIT
  18.                 buffer = new StringBuffer();
  19.                 buffer.append(wordstack.removeLast());
  20.                 index = indexstack.removeLast() + 1;
  21.                 continue;
  22.             }
  23.             String str = buffer.append(sentence.charAt(index)).toString();            if (isWord(str, dic)) {
  24.                 wordstack.add(str);
  25.                 buffer = new StringBuffer();
  26.                 indexstack.add(index);
  27.                 valid = true;
  28.             } else { valid = false; }
  29.             index++;
  30.             if (index == sentence.length() && valid)             //PRINT
  31.                 System.out.println("solution: " + wordstack);
  32.         }
  33.     }

  34.     public static boolean isWord(String word, String[] dic) {
  35.         for (int i=0; i<dic.length; i++)
  36.             if(word.equals(dic[i]))
  37.                 return true;
  38.         return false;
  39.     }
  40. }
复制代码
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册账号
隐私提醒:
  • ☑ 禁止发布广告,拉群,贴个人联系方式:找人请去🔗同学同事飞友,拉群请去🔗拉群结伴,广告请去🔗跳蚤市场,和 🔗租房广告|找室友
  • ☑ 论坛内容在发帖 30 分钟内可以编辑,过后则不能删帖。为防止被骚扰甚至人肉,不要公开留微信等联系方式,如有需求请以论坛私信方式发送。
  • ☑ 干货版块可免费使用 🔗超级匿名:面经(美国面经、中国面经、数科面经、PM面经),抖包袱(美国、中国)和录取汇报、定位选校版
  • ☑ 查阅全站 🔗各种匿名方法

本版积分规则

>
快速回复 返回顶部 返回列表