leetcode刷题(844)——回退字符串比较

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?

很直接的想到用栈来解决(如下),但是题目要求空间复杂度为O(1),所以只能使用其他方法。注意到#只对前面一个字符产生影响,所以从后往前看就是遇到#就把角标移动一个。

class Solution {
    public boolean backspaceCompare(String S, String T) {
        Stack stack1 = new Stack<>();
        Stack stack2 = new Stack<>();        
        char c;       
        for(int i=0;i

 

class Solution {
    public boolean backspaceCompare(String S, String T) {
        int i = S.length()-1;  
        int j = T.length()-1;  
        int skipi = 0;   //记录#数量
        int skipj = 0;  //记录#数量
        
        while(i>=0||j>=0){
            while(i>=0){
                if(S.charAt(i)=='#'){
                    skipi++;  
                    i--;  //碰到#号,往前移动一个
                }else if(skipi>0){ //上面只移动一个而不是直接移动两个的原因就是有可能两个#相连
                    i--;
                    skipi--;
                }else{
                    break;
                }
            }
            while(j>=0){
                if(T.charAt(j)=='#'){
                    skipj++;
                    j--;
                }else if(skipj>0){
                    j--;
                    skipj--;
                }else{
                    break;
                }
            }
            if(i>=0&&j>=0&&S.charAt(i)!=T.charAt(j))
                return false;
            if((i>=0)!=(j>=0))
                return false;
            i--;
            j--;
        }
        return true;
    }
}

 

你可能感兴趣的:(刷题)