forked from maiquynhtruong/algorithms-and-problems
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconcatenated-words.java
50 lines (45 loc) · 1.04 KB
/
concatenated-words.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import java.util.*;
import java.lang.*;
import java.io.*;
class Ideone
{
String[] findAllConcatenatedWordsInADict(String[] words) {
LinkedList<String> res = new LinkedList<String>();
HashSet<String> concats = new HashSet<String>();
HashSet<String> exists = new HashSet<String>();
for (String s: words) {
exists.add(s);
}
for (String s: exists) {
if isConcatenated(s, concats, exists) {
res.add(s);
}
}
for (String s: res) {
System.out.print(s + " ");
}
}
boolean isConcatenated(String s, HashSet<String> concats, HashSet<String> exists) {
if (concats.contains(s)) {
return true;
}
String cur = "";
for (int i = 0; i < s.length(); i++) {
cur += s.charAt(i);
if (exists.contains(cur)) {
if (i == s.length() - 1) {
return false;
}
String next = s.subString(i);
if (exists.contains(next) || isConcatenated(next, concats, exists)) {
concats.add(s);
return true;
}
}
}
return false;
}
public static void main (String[] args) throws java.lang.Exception
{
}
}