Stack-844. 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.

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".
Example 2:

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

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

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

方法1:使用雙棧荠列。

既然回車就是刪除一個字符,那非常符合進(jìn)棧出棧的思路载城。沒遇到一個#就是出棧一個字符(如果椉∷疲空則不管)。以此為思路诉瓦,代碼如下,:

public boolean backspaceCompare2(String S, String T) {
            Stack<Character> s1 = new Stack<>();
            Stack<Character> t1 = new Stack<>();
            for (int i = 0; i < S.length(); i++) {
                if (S.charAt(i) == '#') {
                    if (!s1.empty()) {
                        s1.pop();
                    }
                } else {
                    s1.push(S.charAt(i));
                }
            }

            for (int i = 0; i < T.length(); i++) {
                if (T.charAt(i) == '#') {
                    if (!t1.empty()) {
                        t1.pop();
                    }
                } else {
                    t1.push(T.charAt(i));
                }
            }

            if (s1.size() != t1.size()) {
                return false;
            } else {
                while (!s1.empty()) {
                    Character pop = s1.pop();

                    Character pop1 = t1.pop();

                    if (pop != pop1) {
                        return false;
                    }


                }
            }
            return true;
        }

此方法的時間復(fù)雜度O(M+N)川队, M和N分別是S和T的長度, 空間復(fù)雜度為O(M+N)睬澡, 能否降低空間復(fù)雜度固额?
引入雙指針解法。

方法2 雙指針

每當(dāng)遇到一個#煞聪,代表的前面一個字符可以回退斗躏,
因此分貝將2個字符串從后向前遍歷,遇到一個#則回退一個字符米绕,可以記錄有多少個#瑟捣,代表可以回退的字符個數(shù)。

public boolean backspaceCompare(String S, String T) {
        //
        int s1Len = S.length() - 1;
        int tLen = T.length() - 1;
        int skipS = 0;
        int skipT = 0;
        while (s1Len >= 0 || tLen >= 0) {
            while (s1Len >= 0) {
                if (S.charAt(s1Len) == '#') {
                    skipS++;
                    s1Len--;
                } else if (skipS > 0) {
                    skipS--;
                    s1Len--;
                } else {
                    break;
                }
            }
            while (tLen >= 0) {
                if (T.charAt(tLen) == '#') {
                    skipT++;
                    tLen--;
                } else if (skipT > 0) {
                    skipT--;
                    tLen--;
                } else {
                    break;
                }
            }
            if (s1Len >= 0 && tLen >= 0 && S.charAt(s1Len) != T.charAt(tLen)) {
                return false;
            }
            if ((s1Len >=0 && tLen < 0) || (s1Len <0 && tLen >= 0) ) {
                return false;
            }
            s1Len--;
            tLen--;
        }
        return true;
    }

最后代碼如下:

//Given two strings S and T, return if they are equal when both are typed into e
//mpty 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".
// 
//
// 
// Example 2: 
//
// 
//Input: S = "ab##", T = "c#d#"
//Output: true
//Explanation: Both S and T become "".
// 
//
// 
// Example 3: 
//
// 
//Input: S = "a##c", T = "#a#c"
//Output: true
//Explanation: Both S and T become "c".
// 
//
// 
// Example 4: 
//
// 
//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? 
// 
// 
// 
// 
// 
// Related Topics Two Pointers Stack 
// ?? 1935 ?? 97

package leetcode.editor.en;
//Java:Backspace String Compare

import java.util.Stack;

public class P844BackspaceStringCompare {
    public static void main(String[] args) {
        Solution solution = new P844BackspaceStringCompare().new Solution();
        String s = "a#c";
        String t = "b";
        System.out.println(solution.backspaceCompare(s, t));
        System.out.println("____");
        s = "a##c";
        t = "#a#c";
        System.out.println(solution.backspaceCompare(s, t));
        System.out.println("____");
        // "xywrrmp" "xywrrm#p
        s = "xywrrmp";
        t = "xywrrm#p";
        System.out.println(solution.backspaceCompare(s, t));
        System.out.println("____");
        // "bxj##tw" "bxj###tw"
        s = "bxj##tw";
        t = "bxj###tw";
        System.out.println(solution.backspaceCompare(s, t));
    }
    //leetcode submit region begin(Prohibit modification and deletion)
class Solution {
        /**
         * 雙指針
         * @param S
         * @param T
         * @return
         */
    public boolean backspaceCompare(String S, String T) {
        //
        int s1Len = S.length() - 1;
        int tLen = T.length() - 1;
        int skipS = 0;
        int skipT = 0;
        while (s1Len >= 0 || tLen >= 0) {
            while (s1Len >= 0) {
                if (S.charAt(s1Len) == '#') {
                    skipS++;
                    s1Len--;
                } else if (skipS > 0) {
                    skipS--;
                    s1Len--;
                } else {
                    break;
                }
            }
            while (tLen >= 0) {
                if (T.charAt(tLen) == '#') {
                    skipT++;
                    tLen--;
                } else if (skipT > 0) {
                    skipT--;
                    tLen--;
                } else {
                    break;
                }
            }
            if (s1Len >= 0 && tLen >= 0 && S.charAt(s1Len) != T.charAt(tLen)) {
                return false;
            }
            if ((s1Len >=0 && tLen < 0) || (s1Len <0 && tLen >= 0) ) {
                return false;
            }
            s1Len--;
            tLen--;
        }
        return true;
    }

        /**
         * 棧方法
         * @param S
         * @param T
         * @return
         */
        public boolean backspaceCompare2(String S, String T) {
            Stack<Character> s1 = new Stack<>();
            Stack<Character> t1 = new Stack<>();
            for (int i = 0; i < S.length(); i++) {
                if (S.charAt(i) == '#') {
                    if (!s1.empty()) {
                        s1.pop();
                    }
                } else {
                    s1.push(S.charAt(i));
                }
            }

            for (int i = 0; i < T.length(); i++) {
                if (T.charAt(i) == '#') {
                    if (!t1.empty()) {
                        t1.pop();
                    }
                } else {
                    t1.push(T.charAt(i));
                }
            }

            if (s1.size() != t1.size()) {
                return false;
            } else {
                while (!s1.empty()) {
                    Character pop = s1.pop();

                    Character pop1 = t1.pop();

                    if (pop != pop1) {
                        return false;
                    }


                }
            }
            return true;
        }
}
//leetcode submit region end(Prohibit modification and deletion)

}
image.png
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末栅干,一起剝皮案震驚了整個濱河市迈套,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌碱鳞,老刑警劉巖桑李,帶你破解...
    沈念sama閱讀 219,188評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異,居然都是意外死亡贵白,警方通過查閱死者的電腦和手機(jī)率拒,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,464評論 3 395
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來禁荒,“玉大人猬膨,你說我怎么就攤上這事∏喊椋” “怎么了勃痴?”我有些...
    開封第一講書人閱讀 165,562評論 0 356
  • 文/不壞的土叔 我叫張陵,是天一觀的道長热康。 經(jīng)常有香客問我沛申,道長,這世上最難降的妖魔是什么姐军? 我笑而不...
    開封第一講書人閱讀 58,893評論 1 295
  • 正文 為了忘掉前任铁材,我火速辦了婚禮,結(jié)果婚禮上奕锌,老公的妹妹穿的比我還像新娘著觉。我一直安慰自己,他們只是感情好惊暴,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,917評論 6 392
  • 文/花漫 我一把揭開白布固惯。 她就那樣靜靜地躺著,像睡著了一般缴守。 火紅的嫁衣襯著肌膚如雪葬毫。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,708評論 1 305
  • 那天屡穗,我揣著相機(jī)與錄音贴捡,去河邊找鬼。 笑死村砂,一個胖子當(dāng)著我的面吹牛烂斋,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播础废,決...
    沈念sama閱讀 40,430評論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼汛骂,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了评腺?” 一聲冷哼從身側(cè)響起帘瞭,我...
    開封第一講書人閱讀 39,342評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎蒿讥,沒想到半個月后蝶念,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體抛腕,經(jīng)...
    沈念sama閱讀 45,801評論 1 317
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,976評論 3 337
  • 正文 我和宋清朗相戀三年媒殉,在試婚紗的時候發(fā)現(xiàn)自己被綠了担敌。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,115評論 1 351
  • 序言:一個原本活蹦亂跳的男人離奇死亡廷蓉,死狀恐怖全封,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情桃犬,我是刑警寧澤售貌,帶...
    沈念sama閱讀 35,804評論 5 346
  • 正文 年R本政府宣布,位于F島的核電站疫萤,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏敢伸。R本人自食惡果不足惜扯饶,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,458評論 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望池颈。 院中可真熱鬧尾序,春花似錦、人聲如沸躯砰。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,008評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽琢歇。三九已至兰怠,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間李茫,已是汗流浹背揭保。 一陣腳步聲響...
    開封第一講書人閱讀 33,135評論 1 272
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留魄宏,地道東北人秸侣。 一個月前我還...
    沈念sama閱讀 48,365評論 3 373
  • 正文 我出身青樓,卻偏偏與公主長得像宠互,于是被迫代替她去往敵國和親味榛。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,055評論 2 355