注册一亩三分地论坛,查看更多干货!
您需要 登录 才可以下载或查看附件。没有帐号?注册账号 
x
给一个字典和一个字符串, 打印能顺序抽出的词组成的句子, 同一个词 能重复抽, 但是用过的字tcode 哪题呢
- class Solution {
- public static void main(String[] args) {
- Solution s = new Solution();
- Set<String> d1 = new HashSet<String>();
- d1.addAll(Arrays.asList("i", "live", "love", "ice", "cream", "il", "icream"));
- System.out.print(s.getOutput("iloveicecream", d1));
- }
- public List<List<String>> getOutput(String input, Set<String> dict) {
- List<List<List<String>>> s = new ArrayList<List<List<String>>>();
- s.add(Arrays.asList(new ArrayList<String>()));
- for(int i = 0; i < input.length(); i ++) {
- List<List<String>> ns = buildUp(input, i, dict, s);
- // System.out.println(ns);
- s.add(ns);
- }
- List<List<String>> result = new ArrayList<List<String>>();
- for (int i =0; i < s.size(); i++) {
- for (int j = 1; j < s.get(i).size(); j++) {
- result.add(s.get(i).get(j));
- }
- }
- return result;
- }
- // Search for new matching words in the dictionary and apply it to previous solutions
- public List<List<String>> buildUp(String input,
- int i,
- Set<String> dict,
- List<List<List<String>>> solution) {
- List<List<String>> ns = new ArrayList<List<String>>();
- ns.add(new ArrayList<String>());
- for (int j = i; j >=0 ; j--) {
- String prev = input.substring(j, i+1);
- if (dict.contains(prev)) {
- ns.addAll(getNext(prev, solution.get(j)));
- }
- }
- return ns;
- }
-
- public List<List<String>> getNext(String prev,
- List<List<String>> solution) {
- List<List<String>> ns = new ArrayList<List<String>>();
- for (List<String> sentence: solution) {
- List<String> clone = new ArrayList<String>(sentence);
- clone.add(prev); //
- ns.add(clone);
- }
- return ns;
- }
- }
复制代码
|