第一题
leetcode772
思路:类似这种带括号的体型,都可以通过递归进行求解
比如3{a}4{ad2{cd}}这类都可以
public class 第一题04 {
public static void main(String[] args) {
int res = calculate("15-7*(2-(4+5*3))");
System.out.println(res);
}
public static int calculate(String str){
return f(str.toCharArray(),0)[0];
}
private static int[] f(char[] str, int i) {
int n = str.length;
int cur = 0;
int[] next = null;
LinkedList<String> List = new LinkedList<>();
while (i < n && str[i] != ')'){
if (str[i] >= '0' && str[i] <= '9'){
cur = cur * 10 + (str[i] - '0');
i++;
}else if (str[i] != '('){
//压入栈
addNum(List,cur);
List.push(String.valueOf(str[i]));
i++;
cur = 0;
}else {
next = f(str,i + 1);
cur = next[0];
i = next[1] + 1;
}
}
addNum(List,cur);
return new int[]{getNum(List),i};
}
private static int getNum(LinkedList<String> list) {
int res = 0;
boolean add = true;
while (!list.isEmpty()){
String pop = list.removeFirst();
if (pop.equals("+")){
add = true;
}else if (pop.equals("-")){
add = false;
}else {
int num = Integer.valueOf(pop);
res += add ? num : (-num);
}
}
return res;
}
private static void addNum(LinkedList<String> list, int num) {
if (!list.isEmpty()){
int cur = 0;
String pop = list.pop();
if (pop.equals("+") || pop.equals("-")){
list.push(pop);
}else {
cur = Integer.valueOf(list.pop());
num = pop.equals("*") ? num * cur : cur / num;
}
}
list.push(String.valueOf(num));
}
}
第二题
leetcode11:盛最多水的容器
思路:双指针
public class 第二题04 {
public int maxArea(int[] height) {
int n = height.length;
int left = 0;
int rignt = n - 1;
int ans = 0;
while (left < rignt){
ans = Math.max(ans,(rignt - left) * Math.min(height[left],height[rignt]));
if (height[left] < height[rignt]){
left++;
}else {
rignt--;
}
}
return ans;
}
}
第三题
无效括号变为有效括号的全部合集(好题,重点看递归和剪枝的巧妙处)
思路:递归 + 剪枝
public class 第三题04 {
public static void main(String[] args) {
List<String> allkuohao = allkuohao("((())()()(())()(()");
System.out.println(allkuohao);
}
public static List<String> allkuohao(String s){
ArrayList<String> ans = new ArrayList<>();
remove(s,ans,0,0,new char[]{'(',')'});
return ans;
}
public static void remove(String s, List<String> ans,int checkIndex,int deleteIndex,char[] arr){
int count = 0;
for (int i = checkIndex;i < s.length();i++){
if (s.charAt(i) == arr[0]){
count++;
}else {
count--;
}
if (count < 0){
for (int j = deleteIndex;j <= i;j++){
if (s.charAt(j) == arr[1] && (j == deleteIndex || s.charAt(j - 1) != arr[1])){
remove(s.substring(0,j) + s.substring(j + 1),ans,i,j,arr);
}
}
return;
}
}
String reversed = new StringBuilder(s).reverse().toString();
if (arr[0] == '('){
remove(reversed,ans,0,0,new char[]{')','('});
}else {
ans.add(reversed);
}
}
}