How to split a string into words. Ex: “stringintowords” -> “String Into Words”?

前端 未结 13 1240
粉色の甜心
粉色の甜心 2020-11-29 20:18

What is the right way to split a string into words ? (string doesn\'t contain any spaces or punctuation marks)

For example: \"stringintowords\" -> \"String Into Word

13条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-29 20:29

    A simple Java solution which has O(n^2) running time.

    public class Solution {
        // should contain the list of all words, or you can use any other data structure (e.g. a Trie)
        private HashSet dictionary;
    
        public String parse(String s) {
            return parse(s, new HashMap());
        }
    
        public String parse(String s, HashMap map) {
            if (map.containsKey(s)) {
                return map.get(s);
            }
            if (dictionary.contains(s)) {
                return s;
            }
            for (int left = 1; left < s.length(); left++) {
                String leftSub = s.substring(0, left);
                if (!dictionary.contains(leftSub)) {
                    continue;
                }
                String rightSub = s.substring(left);
                String rightParsed = parse(rightSub, map);
                if (rightParsed != null) {
                    String parsed = leftSub + " " + rightParsed;
                    map.put(s, parsed);
                    return parsed;
                }
            }
            map.put(s, null);
            return null;
        }
    }
    

提交回复
热议问题