241. 为运算表达式设计优先级
使用递归
class Solution {
public List<Integer> diffWaysToCompute(String input) {
if (input.length() == 0) {
return new ArrayList<>();
}
List<Integer> res = new ArrayList<>();
int num = 0, index;
for (index = 0; index < input.length(); index++) {
if (!isOper(input.charAt(index))) {
num = num * 10 + input.charAt(index) - '0';
} else {
break;
}
}
if (index == input.length()) {
res.add(num);
return res;
}
for (int i = 0; i < input.length(); i++) {
char c = input.charAt(i);
if (isOper(c)) {
List<Integer> left = diffWaysToCompute(input.substring(0, i));
List<Integer> right = diffWaysToCompute(input.substring(i + 1));
for (int j = 0; j < left.size(); j++) {
for (int k = 0; k < right.size(); k++) {
res.add(cal(left.get(j), right.get(k), c));
}
}
}
}
return res;
}
private int cal(int a, int b, char c) {
if (c == '+') {
return a + b;
} else if (c == '-') {
return a - b;
} else if (c == '*') {
return a * b;
} else {
return 0;
}
}
private boolean isOper(char c) {
return c == '+' || c == '-' || c == '*';
}
}
242. 有效的字母异位词
class Solution {
public boolean isAnagram(String s, String t) {
int[] arr = new int[26];
for (char c : s.toCharArray()) {
arr[c - 'a']++;
}
for (char c : t.toCharArray()) {
arr[c - 'a']--;
}
for (int i = 0; i < arr.length; i++) {
if (arr[i] != 0) {
return false;
}
}
return true;
}
}