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(); } }
原文地址:https://www.cnblogs.com/zhangyuhao/p/11485464.html
时间: 2024-10-07 03:22:48