题解 | 牛群的秘密通信
牛群的秘密通信
https://www.nowcoder.com/practice/f0047999594d4cd39f85d7347c6941af
- Map.of 无法使用,很有可能这是 Java 8
- 其他都简单,注意使用 values().contains 更方便一些。
import java.util.*; public class Solution { public boolean is_valid_cow_communication (String s) { // Map<Character, Character> map = Map.of(')', '(', '}', '{', ']', '['); Map<Character, Character> map = new HashMap<>(); map.put(')', '('); map.put('}', '{'); map.put(']', '['); Deque<Character> stack = new ArrayDeque<>(); char[] chars = s.toCharArray(); for (int i = 0; i < chars.length; ++i) { if (map.values().contains(chars[i])) { stack.addLast(chars[i]); continue; } if (stack.isEmpty() || map.get(chars[i]) != stack.getLast()) { return false; } else { stack.removeLast(); } } return stack.isEmpty(); } }