-
Notifications
You must be signed in to change notification settings - Fork 19.4k
/
WordPatternMatcher.java
86 lines (77 loc) · 2.97 KB
/
WordPatternMatcher.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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package com.thealgorithms.backtracking;
import java.util.HashMap;
import java.util.Map;
/**
* Class to determine if a pattern matches a string using backtracking.
*
* Example:
* Pattern: "abab"
* Input String: "JavaPythonJavaPython"
* Output: true
*
* Pattern: "aaaa"
* Input String: "JavaJavaJavaJava"
* Output: true
*
* Pattern: "aabb"
* Input String: "JavaPythonPythonJava"
* Output: false
*/
public final class WordPatternMatcher {
private WordPatternMatcher() {
}
/**
* Determines if the given pattern matches the input string using backtracking.
*
* @param pattern The pattern to match.
* @param inputString The string to match against the pattern.
* @return True if the pattern matches the string, False otherwise.
*/
public static boolean matchWordPattern(String pattern, String inputString) {
Map<Character, String> patternMap = new HashMap<>();
Map<String, Character> strMap = new HashMap<>();
return backtrack(pattern, inputString, 0, 0, patternMap, strMap);
}
/**
* Backtracking helper function to check if the pattern matches the string.
*
* @param pattern The pattern string.
* @param inputString The string to match against the pattern.
* @param patternIndex Current index in the pattern.
* @param strIndex Current index in the input string.
* @param patternMap Map to store pattern characters to string mappings.
* @param strMap Map to store string to pattern character mappings.
* @return True if the pattern matches, False otherwise.
*/
private static boolean backtrack(String pattern, String inputString, int patternIndex, int strIndex, Map<Character, String> patternMap, Map<String, Character> strMap) {
if (patternIndex == pattern.length() && strIndex == inputString.length()) {
return true;
}
if (patternIndex == pattern.length() || strIndex == inputString.length()) {
return false;
}
char currentChar = pattern.charAt(patternIndex);
if (patternMap.containsKey(currentChar)) {
String mappedStr = patternMap.get(currentChar);
if (inputString.startsWith(mappedStr, strIndex)) {
return backtrack(pattern, inputString, patternIndex + 1, strIndex + mappedStr.length(), patternMap, strMap);
} else {
return false;
}
}
for (int end = strIndex + 1; end <= inputString.length(); end++) {
String substring = inputString.substring(strIndex, end);
if (strMap.containsKey(substring)) {
continue;
}
patternMap.put(currentChar, substring);
strMap.put(substring, currentChar);
if (backtrack(pattern, inputString, patternIndex + 1, end, patternMap, strMap)) {
return true;
}
patternMap.remove(currentChar);
strMap.remove(substring);
}
return false;
}
}