美文网首页
LeetCode 241-250

LeetCode 241-250

作者: 1nvad3r | 来源:发表于2020-11-23 16:35 被阅读0次

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;
    }
}

相关文章

网友评论

      本文标题:LeetCode 241-250

      本文链接:https://www.haomeiwen.com/subject/dzcviktx.html