1249. Minimum Remove to Make Valid Parentheses
作者:互联网
For this problem, if you can remember, always push the index of '(', the problem can be solved easily.
The solution is:
1. if meet a '(', push the index of it to the stack.
2. if meet a ')', check whether stack is empty, if yes, record the index of ')', if not, pop stack.
3. after the whole string was scanned, record the rest index in the stack.
4. delete the chars which are recorded.
There are at least two ways to record the candidate characters:
1. user char array, mark the candidate character with a special char, if the string only contain '(', ')' and english letters.
public String minRemoveToMakeValid(String s) { char[] cs = s.toCharArray(); Stack<Integer> stk = new Stack<>(); for (int i = 0; i < cs.length; i++) { if (cs[i] == '(') { stk.push(i); } else if (cs[i] == ')') { if (stk.isEmpty()) cs[i] = '?'; else stk.pop(); } } for (int i : stk) { cs[i] = '?'; } String news = new String(cs); //convert char array to string return news.replace("?", ""); }
2. record the index in a list.
public String minRemoveToMakeValid(String s) { List<Integer> list = new ArrayList<>(); Stack<Integer> stk = new Stack<>(); for(int i=0;i<s.length();i++){ if(s.charAt(i)=='('){ stk.push(i); } else if(s.charAt(i)==')'){ if(stk.isEmpty()){ list.add(i); }else stk.pop(); } } while(!stk.isEmpty()){ list.add(stk.pop()); } Collections.sort(list); StringBuilder sb = new StringBuilder(s); for(int i=list.size()-1;i>=0;i--){ sb.deleteCharAt(list.get(i)); //StringBuilder can deleteCharAt(index), but need to delete from back to front } return sb.toString(); }
标签:index,Parentheses,String,Make,Remove,stk,char,record,cs 来源: https://www.cnblogs.com/feiflytech/p/15860014.html