-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWordPattern.java
More file actions
42 lines (31 loc) · 1.16 KB
/
WordPattern.java
File metadata and controls
42 lines (31 loc) · 1.16 KB
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
package String;
import java.util.*;
public class WordPattern{
public static void main(String[] args) {
String pattern = "abba";
String str = "dog dog dog dog";
if(isWordPattern(pattern,str))
System.out.println("TRUE");
else
System.out.println("FALSE");
}
public static boolean isWordPattern(String pattern, String str){
String[] arr = str.split(" ");
//prevent out of boundary problem
if(arr.length != pattern.length())
return false;
HashMap<Character, String> map = new HashMap<Character, String>();
for(int i=0; i<pattern.length(); i++){
char c = pattern.charAt(i);
if(map.containsKey(c)){ //if already present
String value = map.get(c);
if(!value.equals(arr[i])) //if value doesn't mtches with str eg b=dog
return false;
}else if (map.containsValue(arr[i])){
return false;
}
map.put(c, arr[i]);
}
return true;
}
}