码迷,mamicode.com
首页 > 其他好文 > 详细

844. Backspace String Compare

时间:2018-08-28 21:57:35      阅读:211      评论:0      收藏:0      [点我收藏+]

标签:tac   tst   com   tps   turn   als   build   new   Edito   

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

标签:tac   tst   com   tps   turn   als   build   new   Edito   

原文地址:https://www.cnblogs.com/tobeabetterpig/p/9550920.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!