i need combine strings repeated in java this:
- a
- a b
- a b c
- a b d
to have this:
- a b c
- a b d
the problem strings read file, , file have more 10000 lines.
any efficient mode resolve this?
create tree structure has character value:
public class treenode { public character value; public map<character, treenode> childs; public treenode() { childs = new hashmap<character, treenode>(); } }
for each string, read 1 character @ time. every time see "new" character, add root, , if not new, traverse through tree child character has been seen.
once done 1 string, move top of tree (to root) , same thing. "new" character, add child. if value exist within child, move child.
// take list of string input , output combined strings output public list<string> solution(list<string> input) { treenode root = new treenode(); treenode current = root; (string s : input) { (int = 0; < s.length(); i++) { character c = s.charat(i); if (current.childs.containskey(c)) { current = current.childs.get(c); } else { treenode child = new treenode(); child.value = c; current.childs.put(c, child); current = child; } } current = root; } // our tree should complete, bfs on tree unique strings. // traverse tree while constructing string, once reach leaf // add list. return readstrings("", current, new arraylist<string>()); } public list<string> readstrings(string s, treenode current, list<string> ret) { s += current.value; if (current.childs.size() > 0) { (treenode child : current.childs.values()) { readstrings(s, child, ret); } } else { // @ leaf, add ret if (s.length() > 0) { ret.add(s); } } return ret; }
Comments
Post a Comment