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

1047--Remove All Adjacent Duplicates In String

时间:2019-09-08 14:13:04      阅读:76      评论:0      收藏:0      [点我收藏+]

标签:instr   pop   else   ring   lse   har   builder   pre   style   

public class RemoveAllAdjacentDuplicatesInString {
    /*
    解法一:栈
     */
    public String removeDuplicates(String S) {
        Stack<Character> stack=new Stack<>();
        for (char c:S.toCharArray()){
            if (stack.isEmpty()||c!=stack.peek())
                stack.push(c);
            else
                stack.pop();
        }
        StringBuilder stringBuilder=new StringBuilder();
        for (Character character:stack)
            stringBuilder.append(character);
        return stringBuilder.toString();
    }
    /*
    解法二:StringBuilder模拟栈。
     */
    public String removeDuplicates2(String S) {
     StringBuilder stringBuilder=new StringBuilder();
     int length=0;
     for (char c:S.toCharArray()){
        if (length!=0&&c==stringBuilder.charAt(length-1))
            stringBuilder.deleteCharAt(length-- -1);
        else {
            stringBuilder.append(c);
            length++;
        }
     }
     return stringBuilder.toString();
    }
}

 

1047--Remove All Adjacent Duplicates In String

标签:instr   pop   else   ring   lse   har   builder   pre   style   

原文地址:https://www.cnblogs.com/zhangyuhao/p/11485464.html

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