Given two strings S
and T
, return if they are equal when both are typed into empty text editors. #
means a backspace character.
Note that after backspacing an empty text, the text will continue empty.
Example 1:
Input: S = "ab#c", T = "ad#c" Output: true Explanation: Both S and T become "ac".
Approach
Java
import java.util.Stack;public class BackspaceCompare {public static void main(String[] args) {String S = "y#fo##f";String T = "y#f#o##f";System.out.println(backspaceCompare(S, T));}public static boolean backspaceCompare(String S, String T) {Stack<Character> s1 = new Stack<Character>();Stack<Character> s2 = new Stack<Character>();for (int i = 0; i < S.length(); i++) {if (S.charAt(i) == '#' && !s1.isEmpty()) {s1.pop();} else if (S.charAt(i) != '#') {s1.add(S.charAt(i));}}for (int i = 0; i < T.length(); i++) {if (T.charAt(i) == '#' && !s2.isEmpty()) {s2.pop();} else if (T.charAt(i) != '#') {s2.add(T.charAt(i));}}if (s1.size() != s2.size())return false;while (!s1.isEmpty() && !s2.isEmpty()) {if (s1.pop() != s2.pop())return false;}return true;}}
C++
#include <bits/stdc++.h>using namespace std;bool backspaceCompare(string S, string T){stack<char> s1;stack<char> s2;for (int i = 0; i < S.length(); i++){if (S[i] == '#' && !s1.empty()) {s1.pop();} else if (S[i] != '#') {s1.push(S[i]);}}for (int i = 0; i < T.length(); i++) {if (T[i] == '#' && !s2.empty()) {s2.pop();} else if (T[i] != '#') {s2.push(T[i]);}}if (s1.size() != s2.size())return false;while (!s1.empty() && !s2.empty()) {if (s1.top() != s2.top())return false;s1.pop();s2.pop();}return true;}int main(){string S = "y#fo##f";string T = "y#f#o##f";if(backspaceCompare(S, T))cout<<"true";elsecout<<"false";return 0;}
No comments:
Post a Comment