844. Backspace String Compare

Posted tobeabetterpig

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了844. Backspace String Compare相关的知识,希望对你有一定的参考价值。

844. Backspace String Compare


https://leetcode.com/problems/backspace-string-compare/solution/

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".





Solution 1: use stack 

class Solution {
    public boolean backspaceCompare(String S, String T) {
        return shorten(S).equals(shorten(T));
    }
    
    private String shorten(String input){
        Stack<Character> stack = new Stack();
        for(char c : input.toCharArray()){
            if(Character.isLetter(c)){
                stack.push(c);
            }else{
                if(!stack.isEmpty()){
                    stack.pop();
                }
            }
        }
        StringBuilder sb = new StringBuilder();
        for(char c : stack){
            sb.append(c);
        }
        return sb.toString();
    }
}






// solution 2 : 

Wrong result 
class Solution {
    public boolean backspaceCompare(String S, String T) {
        
        return shorten(S).equals(shorten(T));
    }
    private String shorten(String input){
        int count = 0;
        StringBuilder sb = new StringBuilder();
        for(int i = sb.length() - 1; i >= 0; i--){
            char ch = input.charAt(i);
            // if c is a letter 
            if(Character.isLetter(ch)){
                if(count == 0){
                    sb.append(ch);
                }else{
                    count--;
                }
            }else{
                // if c is backspace
                count++;
            }
        }
        return sb.toString();
    }
}



// correct 
class Solution {
    
    private String getString(String str) {
        int n=str.length(), count=0;
        String result="";
        for(int i=n-1; i>=0; i--) {
            char ch=str.charAt(i);
            if(ch==‘#‘) 
                count++;
            else {
                if(count>0)
                    count--;
                else {
                    result+=ch;
                }                     
            }
        }
        return result;
    }
    
    public boolean backspaceCompare(String S, String T) {
        return getString(S).equals(getString(T));
    }
}

 

以上是关于844. Backspace String Compare的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 844. Backspace String Compare

844. Backspace String Compare

844. Backspace String Compare

[LeetCode] 844. Backspace String Compare

(栈,双指针) leetcode. 844 Backspace String Compare

LeetCode_844-Backspace String Compare