新农上路
- 积分
- 99
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2017-2-15
- 最后登录
- 1970-1-1
|
evaluate和follow up的解法,求攒人品
- import java.util.Arrays;
- import java.util.HashMap;
- import java.util.List;
- import java.util.Map;
- public class Solution {
- static boolean evaluate(String s) {
- boolean res = true;
- char lastOp = '&';
- for (int i = 0; i < s.length(); i++) {
- char ch = s.charAt(i);
- if (Character.isLetter(ch)) {
- String tmp = "";
- while (i < s.length() && Character.isLetter(s.charAt(i))) {
- tmp += s.charAt(i);
- i++;
- }
- i--;
- boolean val = tmp.equals("true");
- if (lastOp == '&') {
- res = res && val;
- } else {
- res = res || val;
- }
- } else if (ch == '&' || ch == '|') {
- lastOp = ch;
- } else if (ch == ' ') {
- continue;
- }
- }
- return res;
- }
- static boolean evaluate2(String s, List<String> lst) {
- Map<String, Boolean> map = new HashMap<>();
- for (String str : lst) {
- String[] split = str.split("=");
- if (split[1].equals("true")) {
- map.put(split[0], true);
- } else {
- map.put(split[0], false);
- }
- }
- boolean res = true;
- char lastOp = '&';
- for (int i = 0; i < s.length(); i++) {
- char ch = s.charAt(i);
- if (Character.isLetter(ch)) {
- String tmp = "";
- while (i < s.length() && Character.isLetter(s.charAt(i))) {
- tmp += s.charAt(i);
- i++;
- }
- i--;
- boolean val;
- if (map.containsKey(tmp)) {
- val = map.get(tmp);
- } else {
- val = tmp.equals("true");
- }
- if (lastOp == '&') {
- res = res && val;
- } else {
- res = res || val;
- }
- } else if (ch == '&' || ch == '|') {
- lastOp = ch;
- } else if (ch == ' ') {
- continue;
- }
- }
- return res;
- }
- public static void main(String args[]) {
- System.out.println(evaluate("true | false & true"));
- System.out.println(evaluate("true & false & true"));
- System.out.println(evaluate("true & false | true"));
- System.out.println(evaluate2("a & b | c | true", Arrays.asList("a=true", "b=false", "c=false")));
- }
- }
复制代码 |
|