[LeetCode] 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.

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. 1 <= S.length <= 200
  2. 1 <= T.length <= 200
  3. S and T only contain lowercase letters and '#' characters.

Follow up:

  • Can you solve it in O(N) time and O(1) space?
给2个字符串S和T,里面含有#代表退格键,意味着前面的字符会被删除,判断2个字符串是否相等,字符串中只含有小写字母和#。
解法1:用一个栈存字符,循环字符串,如果是字母就加入栈,遇到#而且栈里面有字母就pop出栈里最后的字符。T: O(n), S:(n)
解法2:follow up要求O(N) time and O(1) space,在一个循环里,从后往前处理字符串,用一个变量记录要删除的字符数量,遇到#时变量加1,遇到字符并且变量大于1,变量减1,直到没遇到#并且要变量为0,这时比较两个字符此时是否一样,不一样返回false,如果字符串比较完没有不一样的字符出现,返回ture。
G家:follow up: 如果有大写键CAP
Java: O(1) space
1
2
3
4
5
6
7
8
9
10
11
12
13
public boolean backspaceCompare(String S, String T) {
        int i = S.length() - 1, j = T.length() - 1;
        while (true) {
            for (int back = 0; i >= 0 && (back > 0 || S.charAt(i) == '#'); --i)
                back += S.charAt(i) == '#' ? 1 : -1;
            for (int back = 0; j >= 0 && (back > 0 || T.charAt(j) == '#'); --j)
                back += T.charAt(j) == '#' ? 1 : -1;
            if (i >= 0 && j >= 0 && S.charAt(i) == T.charAt(j)) {
                i--; j--;
            } else
                return i == -1 && j == -1;
        }
    }

Python:

1
2
3
4
5
6
7
8
9
10
11
12
13
def backspaceCompare(self, S, T):
       i, j = len(S) - 1, len(T) - 1
       backS = backT = 0
       while True:
           while i >= 0 and (backS or S[i] == '#'):
               backS += 1 if S[i] == '#' else -1
               i -= 1
           while j >= 0 and (backT or T[j] == '#'):
               backT += 1 if T[j] == '#' else -1
               j -= 1
           if not (i >= 0 and j >= 0 and S[i] == T[j]):
               return i == j == -1
           i, j = i - 1, j - 1

Python:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# Time:  O(m + n)
# Space: O(1)
import itertools
 
class Solution(object):
    def backspaceCompare(self, S, T):
        """
        :type S: str
        :type T: str
        :rtype: bool
        """
        def findNextChar(S):
            skip = 0
            for i in reversed(xrange(len(S))):
                if S[i] == '#':
                    skip += 1
                elif skip:
                    skip -= 1
                else:
                    yield S[i]
 
        return all(x == y for x, y in
                   itertools.izip_longest(findNextChar(S), findNextChar(T)))

Python: wo O(n) space

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution(object):
    def backspaceCompare(self, S, T):
        """
        :type S: str
        :type T: str
        :rtype: bool
        """
        s1, s2 = [], []
        for i in range(len(S)):
            if S[i] == '#' and s1:
                s1.pop()
            elif S[i] == '#':
                continue
            else:
                s1.append(S[i])
         
        for j in range(len(T)):
            if T[j] == '#' and s2:
                s2.pop()
            elif T[j] == '#':
                continue
            else:
                s2.append(T[j])
         
        return s1 == s2

C++:  

1
2
3
4
5
6
7
8
9
10
11
12
13
bool backspaceCompare(string S, string T) {
        int i = S.length() - 1, j = T.length() - 1;
        while (1) {
            for (int back = 0; i >= 0 && (back || S[i] == '#'); --i)
                back += S[i] == '#' ? 1 : -1;
            for (int back = 0; j >= 0 && (back || T[j] == '#'); --j)
                back += T[j] == '#' ? 1 : -1;
            if (i >= 0 && j >= 0 && S[i] == T[j])
                i--, j--;
            else
                return i == -1 && j == -1;
        }
    }

  

  

 

All LeetCode Questions List 题目汇总

posted @   轻风舞动  阅读(802)  评论(0编辑  收藏  举报
编辑推荐:
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示