中级农民
- 积分
- 102
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2011-2-22
- 最后登录
- 1970-1-1
|
本帖最后由 babyfrog 于 2011-7-19 12:25 编辑
也贴上我的回朔@@
- import java.util.LinkedList;
- public class Sentence {
- public static void main(String[] args) {
- String[] dic = {"a", "apply", "back", "i", "is", "isasen", "sentence", "this", "tence"};
- String sentence = "thisisasentence";
- splitSentence(sentence, dic);
- }
- public static void splitSentence(String sentence, String[] dic) {
- int index = 0;
- boolean valid = true;
- StringBuffer buffer = new StringBuffer();
- LinkedList<String> wordstack = new LinkedList<String>();
- LinkedList<Integer> indexstack = new LinkedList<Integer>();
-
- while (true) {
- if (index == sentence.length()) { //BACKTRACK
- if(indexstack.isEmpty()) break; //EXIT
- buffer = new StringBuffer();
- buffer.append(wordstack.removeLast());
- index = indexstack.removeLast() + 1;
- continue;
- }
- String str = buffer.append(sentence.charAt(index)).toString(); if (isWord(str, dic)) {
- wordstack.add(str);
- buffer = new StringBuffer();
- indexstack.add(index);
- valid = true;
- } else { valid = false; }
- index++;
- if (index == sentence.length() && valid) //PRINT
- System.out.println("solution: " + wordstack);
- }
- }
- public static boolean isWord(String word, String[] dic) {
- for (int i=0; i<dic.length; i++)
- if(word.equals(dic[i]))
- return true;
- return false;
- }
- }
复制代码 |
|