1. 程式人生 > >【LeetCode】Day6 Backspace String Compare

【LeetCode】Day6 Backspace String Compare

今天的題比較簡單,無非是利用棧,加上幾個條件判斷,速度也很快。

題目描述

Given two strings S and T, return if they are equal when both are typed into empty text editors. # means a backspace character.

Example1:

Input: S = "ab#c", T = "ad#c"
Output: true
Explanation: Both S and T become "ac".

Example2:

Input: S = "ab##", T = "c#d#"
Output:
true Explanation: Both S and T become "".

Example3:

Input: S = "a##c", T = "#a#c"
Output: true
Explanation: Both S and T become "c".

Example4:

Input: S = "a#c", T = "b"
Output: false
Explanation: S becomes "c" while T becomes "b".

Note

1 <= S.length <= 200

1 <= T.length <= 200

S and T only contain lowercase letters and '#' characters.

Follow up:

Can you solve it in O(N) time and O(1) space?

題目描述

輸入兩個字串,僅有小寫字母和#,遇到#則刪除上一個元素,操作完畢以後,比較兩個字串,相等反回true,否則返回false

演算法

很簡單,將兩個元素分別入棧,在入棧時,

  • 如果棧不為空且輸入的字元為#,則彈出上一個字元
  • 如果棧為空且輸入的字元為#,則不做任何操作
  • 其他情況正常壓入元素

接下來進行比較兩個字串

  • 如果兩個棧都為空,返回true
  • 如果兩個棧的大小不相等,返回false
  • 如果兩個棧的大小相等,開始迴圈比較兩個棧,如果棧頂不相等,返回false
  • 如果棧頂相等,且棧不為空,就彈出兩個棧的棧頂元素
  • 如果棧為空,返回true

直接看程式碼

#include <iostream>
#include <stack>
#include <string>

using namespace std;
class Solution {
public:
    stack<char> s1;
    stack<char> s2;
    bool backspaceCompare(string S, string T) {
        for(int i = 0; S[i] != '\0';i++){
            if(S[i] != '#'){
                s1.push(S[i]);
            }
            else{
                if(!s1.empty()){
                    s1.pop();
                }
            }
        }


        for(int i = 0; T[i] != '\0';i++){
            if(T[i] != '#'){
                s2.push(T[i]);
            }
            else{
                if(!s2.empty()){
                    s2.pop();
                }
            }
        }
        if(s1.empty() && s2.empty()){
            return true;
        }

        if(s1.size() != s2.size()){
            return false;
        }
        else{
            for(int i = 0 ; !s1.empty() ;i++){
                if(s1.top() != s2.top()){
                    return false;
                }
                else{
                    s1.pop();
                    s2.pop();
                }
                if(s1.empty() || s2.empty()){
                    return true;
                }
            }
        }
    }
};
int main()
{
    Solution s;
    string a = "xywrrmp";
    string b = "xywrrmu#p";
    cout << s.backspaceCompare(a , b) << endl;
    cout << "Hello world!" << endl;
    return 0;
}