-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathProblem_10_Comparing_Strings_containing_Backspaces.java
45 lines (35 loc) · 1.43 KB
/
Problem_10_Comparing_Strings_containing_Backspaces.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
package Two_Pointers;
// Problem Statement: Comparing Strings containing Backspaces (medium)
// LeetCode Question: 844. Backspace String Compare
public class Problem_10_Comparing_Strings_containing_Backspaces {
public boolean compare(String str1, String str2) {
// use two pointer approach to compare the strings
int index1 = str1.length() - 1, index2 = str2.length() - 1;
while (index1 >= 0 || index2 >= 0) {
int i1 = getNextValidCharIndex(str1, index1);
int i2 = getNextValidCharIndex(str2, index2);
if (i1 < 0 && i2 < 0) // reached the end of both the strings
return true;
if (i1 < 0 || i2 < 0) // reached the end of one of the strings
return false;
if (str1.charAt(i1) != str2.charAt(i2)) // check if the characters are equal
return false;
index1 = i1 - 1;
index2 = i2 - 1;
}
return true;
}
private static int getNextValidCharIndex(String str, int index) {
int backspaceCount = 0;
while (index >= 0) {
if (str.charAt(index) == '#') // found a backspace character
backspaceCount++;
else if (backspaceCount > 0) // a non-backspace character
backspaceCount--;
else
break;
index--; // skip a backspace or a valid character
}
return index;
}
}