leetcode 844. Backspace String Compare(python)

描述

Given two strings s and t, return true 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".

Note:

1 <= s.length, t.length <= 200
s and t only contain lowercase letters and '#' characters.

解析

根据题意,# 符号代表了键盘上面的退格键,判断两个字符串在执行了退格键之后是否相等。思路比较简单,构建一个函数 make,遍历字符串 n ,如果字符不是 # 则添加到列表 r 中,如果是 # 则当 r 不为空的时候对列表 r 执行 r.pop(-1) ,最后得到的列表转换成字符串,判断 make(s) 和 make(t) 是否相等。

解答

class Solution(object):
    def backspaceCompare(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """    
        def make(n):
            r = []
            for c in n:
                if c != '#':
                    r.append(c)
                else:
                    if r:
                        r.pop(-1)
            return ''.join(r)
        return make(s) == make(t)

运行结果

Runtime: 24 ms, faster than 32.81% of Python online submissions for Backspace String Compare.
Memory Usage: 13.5 MB, less than 57.48% of Python online submissions for Backspace String Compare.

原题链接:https://leetcode.com/problems/backspace-string-compare/

您的支持是我最大的动力

你可能感兴趣的:(leetcode,leetcode,算法,python)