【leetcode】1047. 删除字符串中的所有相邻重复项(JAVA + 栈)+ 本地调用测试

【leetcode】1047. 删除字符串中的所有相邻重复项(JAVA + 栈)+ 本地调用测试_第1张图片

写法一

class Solution {
    public String removeDuplicates(String s) {
        Stack<Character> st = new Stack<Character>();
        if(s.length() == 0 ){
            return "";
        }
        st.push(s.charAt(0));
        for(int i = 1; i < s.length(); i++){
            if(!st.empty() && s.charAt(i) == st.peek()){
                st.pop();
            }else {
                st.push(s.charAt(i));
            }
        }
        String str = "";
        while(!st.empty()){
            str = st.pop() + str;
        }
        return str;      
    }
}

写法二

class Solution {
    public String removeDuplicates(String s){
        StringBuffer stack = new StringBuffer();
        int top = -1;
        for(int i = 0; i < s.length(); i++){
            char ch = s.charAt(i);
            if(top >= 0 && stack.charAt(top) == ch){
                stack.deleteCharAt(top);
                top--;
            }else{
                stack.append(ch);
                top++;
            }
        }
        return stack.toString();
    }
}

本地测试

package leetcode;
import java.util.Stack;

public class lc_1047_removeDuplicates {

    public String removeDuplicates(String s) { // AC

        Stack<Character> st = new Stack<Character>();
        if(s.length() == 0 ){
            return "";
        }
        st.push(s.charAt(0));
        for(int i = 1; i < s.length(); i++){
            if(!st.empty() && s.charAt(i) == st.peek()){
                st.pop();
            }else {
                st.push(s.charAt(i));
            }
        }
        String str = "";
        while(!st.empty()){
            str = st.pop() + str;
        }
        return str;
    }

    public static void main(String[] args) {

        String s = "abbaca"; // "ca"
//        String s = "aababaab"; // "ba"
//        String s = "aaaaaaaaa"; // "a"
//        String s = "abbbabaaa"; // "ababa"
        lc_1047_removeDuplicates dup = new lc_1047_removeDuplicates();
        String ans = dup.removeDuplicates(s);
        System.out.println(ans);
    }
}

你可能感兴趣的:(Leetcode,JAVA,java,leetcode,开发语言)