标签:ali tac string char info ack java 移除 cti
括号先后成对出现,适合使用栈结构进行处理。
JAVA :
public final String minRemoveToMakeValid(String s) { if (s == null || s.length() == 0) return ""; StringBuilder sb = new StringBuilder(); Stack<Integer> stack = new Stack<Integer>(); int len = s.length(); char[] sChar = s.toCharArray(); for (int i = 0; i < len; i++) { if (sChar[i] == ‘(‘) stack.push(i); else if (sChar[i] == ‘)‘) { if (!stack.empty()) stack.pop(); else sChar[i] = ‘-‘; } } for (Integer prePoint : stack) sChar[prePoint] = ‘-‘; for (int i = 0; i < len; i++) { if (sChar[i] != ‘-‘) sb.append(sChar[i]); } return sb.toString(); }
JS:
var minRemoveToMakeValid = function (s) { let stack = [], len = s.length, sChar = s.split(‘‘); for (let i = 0; i < len; i++) { if (sChar[i] == ‘(‘) stack.push(i); else if (sChar[i] == ‘)‘) { if (stack.length == 0) sChar[i] = ‘-‘; else stack.pop(); } } for (let i = 0; i < stack.length; i++) sChar[stack[i]] = ‘-‘; s = sChar.join(‘‘); s = s.replace(/-/g, ‘‘); return s; };
标签:ali tac string char info ack java 移除 cti
原文地址:https://www.cnblogs.com/niuyourou/p/14191029.html