/**
* // This is the interface that allows for creating nested lists.
* // You should not implement it, or speculate about its implementation
* public interface NestedInteger {
* // Constructor initializes an empty nested list.
* public NestedInteger();
*
* // Constructor initializes a single integer.
* public NestedInteger(int value);
*
* // @return true if this NestedInteger holds a single integer, rather than a nested list.
* public boolean isInteger();
*
* // @return the single integer that this NestedInteger holds, if it holds a single integer
* // Return null if this NestedInteger holds a nested list
* public Integer getInteger();
*
* // Set this NestedInteger to hold a single integer.
* public void setInteger(int value);
*
* // Set this NestedInteger to hold a nested list and adds a nested integer to it.
* public void add(NestedInteger ni);
*
* // @return the nested list that this NestedInteger holds, if it holds a nested list
* // Return null if this NestedInteger holds a single integer
* public List<NestedInteger> getList();
* }
*/
class Solution {
public NestedInteger deserialize(String s)
{
if(s==null || s.length()==0)
return null;
NestedInteger cur=null;
Stack<NestedInteger> st=new Stack<>();
int sign=1,num=0;
for(int i=0;i<s.length();i++)
{
char c=s.charAt(i);
if(c=='[')
st.push(new NestedInteger());
else if(c=='-')
sign=-1;
else if(Character.isDigit(c))
{
int j=i;
while(j<s.length() && Character.isDigit(s.charAt(j)))
{
num=num*10+s.charAt(j)-'0';
j++;
}
i=j-1;
if (st.isEmpty()) {
cur = new NestedInteger(sign*num);
break;
}
st.peek().add(new NestedInteger(sign*num));
sign=1;
}
else if(c==']')
{
cur=st.pop();
if(st.isEmpty())
break;
st.peek().add(cur);
}
else
num=0;
}
return cur;
}
}
241. Different Ways to Add Parentheses
算法一
class Solution {
public List<Integer> diffWaysToCompute(String input) {
return recursive(input);
}
public List<Integer> recursive(String input){
LinkedList<Integer> res=new LinkedList<>();
if(input.equals(""))
return res;
for(int i=0;i<input.length();i++)
{
char c=input.charAt(i);
if(c=='+'|| c=='-'|| c=='*'){
List<Integer> left=recursive(input.substring(0,i));
List<Integer> right=recursive(input.substring(i+1));
for(int a:left){
for(int b:right){
if(c=='+')
res.add(a+b);
if(c=='-')
res.add(a-b);
if(c=='*')
res.add(a*b);
}
}
}
}
if(res.size()==0)
res.add(Integer.valueOf(input));
return res;
}
}
算法二:
class Solution {
List<Integer>[][] dp = null;
public List<Integer> diffWaysToCompute(String input) {
int n = input.length();
dp = new ArrayList[n][n];
eval(input, 0, n-1);
return dp[0][n-1];
}
private void eval(String s, int i, int j){
if(dp[i][j] != null) return;
dp[i][j] = new ArrayList<>();
List<Integer> res = new ArrayList<>();
for(int k=i; k <= j; k++){
char op = s.charAt(k);
if( op == '+' || op == '-' || op == '*'){
eval(s, 0, k-1);
eval(s, k+1, j);
for(int val1 : dp[i][k-1])
for(int val2 : dp[k+1][j])
res.add(calc(val1, op, val2));
}
}
if(res.isEmpty()){
dp[i][j].add(Integer.valueOf(s.substring(i,j+1)));
return;
}
dp[i][j] = res;
}
private int calc(int n1, char op, int n2){
if(op == '+')
return n1+n2;
else if(op == '-')
return n1-n2;
else if(op == '*')
return n1*n2;
return 0;
}
}
class Solution {
public static List<String> ret;
public List<String> addOperators(String num, int target) {
ret=new LinkedList<>();
backtrace(num,new StringBuilder(),target,0,0,0);
return ret;
}
public static void backtrace(String num,StringBuilder sb,int target,int start,long pre,long sum){
if(start==num.length())
{
if(sum==target)
ret.add(sb.toString());
return;
}
for(int i=start;i<num.length();i++){
if(num.charAt(start)=='0' && i>start)
break;
long val=Long.valueOf(num.substring(start,i+1));
int len=sb.length();
if(start==0){
backtrace(num,sb.append(val),target,i+1,val,sum+val);
sb.setLength(len);
}else{
backtrace(num,sb.append('+').append(val),target,i+1,val,sum+val);
sb.setLength(len);
backtrace(num,sb.append('-').append(val),target,i+1,-val,sum-val);
sb.setLength(len);
backtrace(num,sb.append('*').append(val),target,i+1,pre*val,sum-pre+pre*val);
sb.setLength(len);
}
}
}
}
class Solution {
public int calculate(String s) {
int num=0;
char sign='+';
Stack<Integer> stack=new Stack<>();
for(int i=0;i<s.length();i++){
char c=s.charAt(i);
if(Character.isDigit(c))
num=num*10+c-'0';
if((!Character.isDigit(c) && c!=' ') || i==s.length()-1){
if(sign=='+')
stack.push(num);
if(sign=='-')
stack.push(-num);
if(sign=='*')
stack.push(stack.pop()*num);
if(sign=='/')
stack.push(stack.pop()/num);
num=0;
sign=c;
}
}
int sum=0;
while(!stack.isEmpty())
sum+=stack.pop();
return sum;
}
}
class Solution {
public String removeKdigits(String num, int k) {
if(num.length()<=k)
return "0";
int K=k;
Stack<Character> stack=new Stack<>();
char[] charArray=num.toCharArray();
for(int i=0;i<charArray.length;i++){
while(!stack.isEmpty() && stack.peek()>charArray[i] && k>0){
stack.pop();
k--;
}
stack.push(charArray[i]);
}
while(k>0){
stack.pop();
k--;
}
char[] ret=new char[num.length()-K];
for(int i=ret.length-1;i>=0;i--)
ret[i]=stack.pop();
int i=0;
while(i<ret.length && ret[i]=='0')
i++;
return i==ret.length?"0":new String(ret).substring(i);
}
}
865. 字符串展开
思路一:
利用递归(深度优先搜索),递归代码不太容易bugfree,需要理清楚逻辑顺序。
import java.util.Scanner;
class Main {
public static int idx;
public static String dfs(String s) {
String res = "";
while (idx < s.length())
{
char tmp = s.charAt(idx);
if (tmp == '#') return res;
if (tmp >= '0' && tmp <= '9')
{
int num = 0;
while (idx<s.length() && s.charAt(idx) != '%')
{
num = s.charAt(idx) - '0' + num * 10;
idx++;
}
idx++;
String inner = dfs(s);
while (num > 0)
{
res += inner;
num--;
}
}
else
res += tmp;
idx++;
}
return res;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String s = in.nextLine();
idx=0;
System.out.println(solve(s));
}
}
解法二:
借助栈,处理起来比较复杂,跟上面的算式字符串解析类似
import java.util.Scanner;
import java.util.LinkedList;
class Main {
public static boolean isAlpha(char c)
{
return (c>='a' && c<='z') || (c>='A' && c<='Z');
}
public static String solve(String s){
LinkedList<String> ll=new LinkedList<>();
for(int i=0;i<s.length();i++)
{
if(s.charAt(i)>='0' && s.charAt(i)<='9')
{
int num=0;
int j=i;
while(j<s.length() && s.charAt(j)>='0' && s.charAt(j)<='9')
{
num=num*10+s.charAt(j)-'0';
j++;
}
ll.add(String.valueOf(num));
if(j>i)
i=j-1;
}
else if(s.charAt(i)=='#')
{
String target="",res="";
while(!ll.peekLast().equals("%"))
target=ll.pollLast()+target;
ll.pollLast();
int n=Integer.valueOf(ll.pollLast());
for(int j=0;j<n;j++)
res+=target;
ll.add(res);
}
else if(s.charAt(i)=='%')
{
ll.add(String.valueOf(s.charAt(i)));
}
else
{
int j=i;
String tmp="";
while(j<s.length() && isAlpha(s.charAt(j)))
{
tmp+=s.charAt(j);
j++;
}
ll.add(tmp);
if(j>i)
i=j-1;
}
}
StringBuilder ret=new StringBuilder();
while(!ll.isEmpty())
{
String tmp=ll.pollFirst();
ret.append(tmp);
}
return ret.toString();
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String s = in.nextLine();
idx=0;
System.out.println(solve(s));
}
}