-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathWordPattern.java
53 lines (52 loc) · 1.72 KB
/
WordPattern.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
51
52
53
/*https://leetcode.com/problems/word-pattern/*/
class Solution {
public boolean wordPattern(String pattern, String s) {
HashMap<String,Character> map = new HashMap<String,Character>();
HashMap<Character,String> rev = new HashMap<Character,String>();
StringBuilder build = new StringBuilder("");
String word = "";
int N = s.length(), p = 0;
char ch;
for (int i = 0; i < N; ++i)
{
ch = s.charAt(i);
if (ch != ' ')
build.append(ch);
else
{
word = build.toString();
if (p >= pattern.length()) return false;
if (map.containsKey(word))
{
if (map.get(word) != pattern.charAt(p)) return false;
}
else if (rev.containsKey(pattern.charAt(p)) && rev.get(pattern.charAt(p)) != word)
{
return false;
}
else
{
map.put(word,pattern.charAt(p));
rev.put(pattern.charAt(p),word);
}
++p;
build = new StringBuilder("");
}
}
word = build.toString();
if (p >= pattern.length()) return false;
if (map.containsKey(word))
{
if (map.get(word) != pattern.charAt(p)) return false;
}
else if (rev.containsKey(pattern.charAt(p)) && rev.get(pattern.charAt(p)) != word) return false;
else
{
map.put(word,pattern.charAt(p));
rev.put(pattern.charAt(p),word);
}
++p;
if (p < pattern.length()) return false;
return true;
}
}