給定 s 和 t 兩個字符串,當它們分別被輸入到空白的文本編輯器后,如果兩者相等,返回 true 。# 代表退格字符。
注意:如果對空文本輸入退格字符,文本繼續為空。
示例 1:
輸入:s = “ab#c”, t = “ad#c”
輸出:true
解釋:s 和 t 都會變成 “ac”。
示例 2:
輸入:s = “ab##”, t = “c#d#”
輸出:true
解釋:s 和 t 都會變成 “”。
示例 3:
輸入:s = “a#c”, t = “b”
輸出:false
解釋:s 會變成 “c”,但 t 仍然是 “b”。
提示:
1 <= s.length, t.length <= 200
s 和 t 只含有小寫字母以及字符 ‘#’
進階:
你可以用 O(n) 的時間復雜度和 O(1) 的空間復雜度解決該問題嗎?
雙指針,兩個指針開始時各自指向兩個字符串尾部,然后向前遍歷即可:
class Solution {
public:bool backspaceCompare(string s, string t) {int sIdx = s.size() - 1;int tIdx = t.size() - 1;int sDelete = 0;int tDelete = 0;while (sIdx >= 0 && tIdx >= 0) {if (s[sIdx] == '#') {--sIdx;++sDelete;continue;}if (t[tIdx] == '#') {--tIdx;++tDelete;continue;}if (sDelete > 0) {--sIdx;--sDelete;continue;}if (tDelete > 0) {--tIdx;--tDelete;continue;}if (s[sIdx] != t[tIdx]) {return false;}--sIdx;--tIdx;}// 以上循環結束時,可能s或t其中一個還沒有遍歷完// s尚未遍歷完,由于t已被遍歷完,因此接下來s中不可以出現刪不掉的字符while (sIdx >= 0) {if (s[sIdx] == '#') {--sIdx;++sDelete;continue;}if (sDelete > 0) {--sIdx;--sDelete;continue;}return false;}while (tIdx >= 0) {if (t[tIdx] == '#') {--tIdx;++tDelete;continue;}if (tDelete > 0) {--tIdx;--tDelete;continue;}return false;}return true;}
};
如果s的長度為n,t的長度為m,則此算法時間復雜度為O(n+m),空間復雜度為O(1)。