-
Notifications
You must be signed in to change notification settings - Fork 1
/
Day 50.2.txt
68 lines (53 loc) · 1.67 KB
/
Day 50.2.txt
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
290. Word Pattern
Given a pattern and a string s, find if s follows the same pattern.
Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in s.
Example 1:
Input: pattern = "abba", s = "dog cat cat dog"
Output: true
Example 2:
Input: pattern = "abba", s = "dog cat cat fish"
Output: false
Example 3:
Input: pattern = "aaaa", s = "dog cat cat dog"
Output: false
Example 4:
Input: pattern = "abba", s = "dog dog dog dog"
Output: false
Constraints:
1 <= pattern.length <= 300
pattern contains only lower-case English letters.
1 <= s.length <= 3000
s contains only lower-case English letters and spaces ' '.
s does not contain any leading or trailing spaces.
All the words in s are separated by a single space.
class Solution {
public boolean wordPattern(String p, String s) {
List<String> nm=new ArrayList<>();
int i,j=0;
for(i=1;i<s.length();i++)
{
if(s.charAt(i)==' ')
{
nm.add(s.substring(j,i));
j=i+1;
}
}
nm.add(s.substring(j,i));
if(nm.size()!=p.length())
return false;
HashMap<String,Character> kk=new HashMap<>();
for(i=0;i<nm.size();i++)
{
if(kk.containsKey(nm.get(i)))
{
if(kk.get(nm.get(i))!=p.charAt(i))
return false;
}
if(kk.containsValue(p.charAt(i))&&!kk.containsKey(nm.get(i)))
return false;
else
kk.put(nm.get(i),p.charAt(i));
}
return true;
}
}