【LeetCode】844. Backspace String Compare 解題報告(Python)

做者: 負雪明燭
id: fuxuemingzhu
我的博客: http://fuxuemingzhu.cn/python


題目地址:https://leetcode.com/problems/backspace-string-compare/description/c#

題目描述

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

Example 1:編輯器

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

Example 2:ide

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

Example 3:spa

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

Example 4:code

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

Note:ip

  1. 1 <= S.length <= 200
  2. 1 <= T.length <= 200
  3. S and T only contain lowercase letters and ‘#’ characters.

Follow up:leetcode

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

題目大意

在一個空白的編輯器裏連續輸入兩段字符,其中#表明退格,要求最後兩段字符是否相同。字符串

有個Follow up,問咱們能不能使用O(n)的時間複雜度和O(1)的空間複雜度。

解題方法

字符串切片

字符串題對於Python而言都不算題。就是按照題目要求作一遍就行了。

遇到#,字符串不爲空,就刪除最後一個字符。若是不是#號,就拼接到字符串的最後。把兩個字符串都求出來,而後比較就好。

注意,我不當心踏進了一個坑,由於看到兩個連續的if,就把它們合併在一塊兒了,其實不行的:

if s == '#':
    if ans_S:
        ans_S = ans_S[:-1]

我給改爲了:

if s == '#' and ans_S:
        ans_S = ans_S[:-1]

這樣看着好看了,實際上是錯的。由於若是字符串是空的,那麼輸入#號,會把這個#號拼接到字符串上去。

Follow up的要求暫時不會。

代碼以下:

class Solution(object):
    def backspaceCompare(self, S, T):
        """ :type S: str :type T: str :rtype: bool """
        ans_S = ""
        ans_T = ""
        for s in S:
            if s == '#':
                if ans_S:
                    ans_S = ans_S[:-1]
            else:
                ans_S += s
        for t in T:
            if t == '#':
                if ans_T:
                    ans_T = ans_T[:-1]
            else:
                ans_T += t
        return ans_S == ans_T

使用一個棧的話,能夠完美處理這個問題,遇到#退棧就行了,惟一須要注意的時候若是棧是空的時候,不能退棧。

class Solution(object):
    def backspaceCompare(self, S, T):
        """ :type S: str :type T: str :rtype: bool """
        stackS, stackT = [], []
        for s in S:
            if s != "#":
                stackS.append(s)
            elif stackS:
                stackS.pop()
        for t in T:
            if t != "#":
                stackT.append(t)
            elif stackT:
                stackT.pop()
        return stackS == stackT

日期

2018 年 6 月 10 日 —— 等了兩天的騰訊比賽複賽B的數據集,結果人家在複賽剛開始就給了。。

相關文章
相關標籤/搜索