classSolution{ //判断字符串是否有效,()[]{} publicbooleanIsValidExp(String s){ if (s == null || s.length() == 0) { returntrue; } // write code here Stack<Character> stack = new Stack<>(); int i = 0; int l = s.length(); while (i < l) { char c = s.charAt(i); char out; if (c == '(' || c == '[' || c == '{') { stack.push(c); } else { if (stack.isEmpty()) { returnfalse; } if (c == ')') { out = stack.pop(); if (out == '[' || out == '{') { returnfalse; } } elseif (c == ']') { out = stack.pop(); if (out == '(' || out == '{') { returnfalse; } } elseif (c == '}') { out = stack.pop(); if (out == '(' || out == '[') { returnfalse; } }
} i++;
} return stack.isEmpty(); } }
3.找零问题,最少找多少硬币
解法1贪心:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
classSolution{ publicintGetCoinCount(int N){ //dp // write code here int sub = 1024 - N; int res = 0; res += sub/64; sub %= 64; res += sub/16; sub %= 16; res += sub/4; sub %= 4; res += sub/1; return res; } }