844--Backspace String Compare

public class BackspaceStringCompare {
    /*
    解法一:从头扫描:用栈的思想,遇到#,则出栈。
     */
    public static boolean backspaceCompare(String S, String T) {
        return getString(S).equals(getString(T));
    }
    private static String getString(String s){
        StringBuilder sb=new StringBuilder();
        for (char ch:s.toCharArray()){
            if (ch!='#')
                sb.append(ch);
            else if (sb.length()>0)
                sb.deleteCharAt(sb.length()-1);
        }
        return sb.toString();
    }
    /*
    解法二:从尾扫描:遇到#,则不要下一个。
     */
    public static boolean backspaceCompare2(String S, String T) {
        return getString(S).equals(getString(T));
    }
    private static String getString(String s){
        StringBuilder sb=new StringBuilder();
        int count=0;
        char c;
        for (int i=s.length()-1;i>=0;i--){
            c=s.charAt(i);
            if (c=='#')
                count++;
            else {
                if (count>0)
                    count--;
                else
                    sb.append(c);
            }
        }
        return sb.toString();
    }
}

 

你可能感兴趣的:(844--Backspace String Compare)