Skip to content

Commit

Permalink
844. Backspace String Compare (#39)
Browse files Browse the repository at this point in the history
* 844. Backspace String Compare

* Add missing link
  • Loading branch information
xtenzQ authored Jul 30, 2024
1 parent fba0fc1 commit ca83de2
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -56,4 +56,33 @@ public static String removeDuplicates(String s) {
}
return sb.toString();
}

/**
* Given two strings {@code s} and {@code t}, return {@code true} if they are equal when both are typed
* into empty text editors. {@code #} means a backspace character.
*
* @param s first string
* @param t second string
* @return {@code true} if strings are equal, {@code false} otherwise
* @implNote This method runs in {@code O(n + m} time and space complexity, where {@code n} and {@code m} are
* the lengths of strings {@code s} and {@code t}
* @see <a href="https://leetcode.com/problems/backspace-string-compare/">844. Backspace String Compare</a>
*/
public static boolean backspaceCompare(String s, String t) {
Stack<Character> sStack = clearStack(s);
Stack<Character> tStack = clearStack(t);
return tStack.equals(sStack);
}

private static Stack<Character> clearStack(String s) {
Stack<Character> stack = new Stack<>();
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) != '#') {
stack.push(s.charAt(i));
} else if (!stack.empty()) {
stack.pop();
}
}
return stack;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import org.junit.jupiter.api.Test;

import static com.xtenzq.stack.Stacks.backspaceCompare;
import static com.xtenzq.stack.Stacks.isValid;
import static com.xtenzq.stack.Stacks.removeDuplicates;
import static org.junit.jupiter.api.Assertions.assertEquals;
Expand Down Expand Up @@ -34,4 +35,19 @@ void removeDuplicates_test1() {
void removeDuplicates_test2() {
assertEquals("ay", removeDuplicates("azxxzy"));
}

@Test
void backspaceCompare_case1() {
assertTrue(backspaceCompare("ab#c", "ad#c"));
}

@Test
void backspaceCompare_case2() {
assertTrue(backspaceCompare("ab##", "c#d#"));
}

@Test
void backspaceCompare_case3() {
assertFalse(backspaceCompare("a#c", "b"));
}
}

0 comments on commit ca83de2

Please sign in to comment.