【LeetCode算法題】-Backspace String Compare

一、看題和準備

今天介紹的是LeetCode算法題中Easy級別的第197題(順位題號是844)。給定兩個字符串S和T,如果兩個字符串都輸入到空文本編輯器中並且相等,則返回true。 #表示退格符。例如:


輸入:S =“ab#c”,T =“ad#c”

輸出:true

說明:S和T都變爲“ac”。


輸入:S =“ab ##”,T =“c#d#”

輸出:true

說明:S和T都變爲“”。


輸入:S =“a ## c”,T =“#a#c”

輸出:true

說明:S和T都變爲“c”。


輸入:S =“a#c”,T =“b”

輸出:false

說明:S變爲“c”而T變爲“b”。


注意

  • 1 <= S.length <= 200

  • 1 <= T.length <= 200

  • S和T僅包含小寫字母和“#”字符。

跟進:能在O(N)時間和O(1)空間解決它嗎?


本次解題使用的開發工具是InteIIiJ IDEA,jdk使用的版本是1.8,環境是win10 64位系統,使用Java語言編寫和測試。

二、第一種解法

通過棧的用法,先轉換成新的字符串,只不過是使用棧來實現,藉助其先進後廚的特性。

先遍歷字符串中的字符,如果當前字符不是#號,就入棧;如果遇到#號,就需要回退一個字符,只要將棧頂的元素出棧即可,但是先判斷棧中是否包含元素。。

public static  boolean Compare(String S,String T){
        return build(S).equals(build(T));
    }
    public  static  String build(String str){
        Stack<Character> stack = new Stack<>();
        for (char ch:str.toCharArray()
             ) {
            if (ch!='#'){
                stack.push(ch);
            }else if(!stack.isEmpty()){
                stack.pop();
            }
        }
        return String.valueOf(stack);
    }

三、第二種解法

從後向前遍歷字符串中的字符,統計遇到的#號個數,直到遇到字母爲止,然後累加字符,變成一個新的字符串,另外的同理。

 public static boolean backspaceCompare(String S,String T){
        return rebuild(S).equals(rebuild(T));
    }
    public static String rebuild(String str){
        String newStr = "";
        int count = 0;
        for (int i=str.length()-1;i>=0;i--) {
            char ch = str.charAt(i);
            if(ch=='#'){
                count++;
            }else {
                if(count>0){
                    count--;
                }else{
                    newStr += ch;
                }
            }
        }
        return newStr;
    }

四、第三種解法

  public  static boolean backspaceCompare3(String S,String T){
        int i = S.length()-1,j=T.length()-1;
        while(S.length()-1>=0||T.length()-1>=0){
            i = helper(S,i);
            j = helper(T,j);
            //判斷當前的i和j對應的字符串是否相等
            if(i>=0 && j>=0 && S.charAt(i)!=T.charAt(j)){
                return false;
            }
            //如果i或者j小於0時,判斷兩者是否同時小於0
            if(i<0||j<0){
                return i==j;
            }
            i--;
            j--;
        }
        return true;
    }
    public static int helper(String str,int index){
        int  count = 0;
        while(index>0){
            if(str.charAt(index)=='#'){
                count++;
                index--;
            }else if(count >0){
                count--;
                index--;
            } else {
                break;
            }
        }
        return index;
    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章