JAVA一些语法整理:
Queue:
Queue<String> queue = new LinkedList<String>();
queue.offer("a"); // 添加一个元素并返回true
queue.poll(); // get and pop the first element
queue.peek(); // 返回队列头部的元素
Stack:
Stack<TreeNode> stack = new Stack<TreeNode>();
stack.push(root);
stack.pop();
stack.peek(); // 查看最后一个元素,但不删除
stack.empty(); // 返回bollean
LinkedList:
List<String> res = new LinkedList<>();
res.toArray(new String[0]); // 转array
res.remove(0); // 按位置删除
ArrayList:
List<String> list=new ArrayList<String>();
list.add("Hello");
ArrayList<Integer> list = new ArrayList<Integer>();
数组:
int list[] = {1, 2, 3};
for(int i=0; i < re.length; i++) {
System.err.println(re[i]);
}
===================================
500. Keyboard Row
class Solution {
public String[] findWords(String[] words) {
String[] strs = {"QWERTYUIOP","ASDFGHJKL","ZXCVBNM"};
Map<Character, Integer> map = new HashMap<>();
for (int i=0; i < strs.length; i++){
for (char c: strs[i].toCharArray()){
map.put(c, i);
}
}
List<String> res = new LinkedList<>();
for (String w: words){
if (w.equals("")) continue;
int index = map.get(w.toUpperCase().charAt(0));
for (char c: w.toUpperCase().toCharArray()){
if (map.get(c) != index){
index = -1;
break;
}
}
if (index != -1) res.add(w);
}
return res.toArray(new String[0]);
}
}
437. Path Sum III
class Solution {
public int pathSum(TreeNode root, int sum) {
if (root == null) return 0;
return getSum(root, sum) + pathSum(root.left, sum) + pathSum(root.right, sum);
}
public int getSum(TreeNode node, int sum){
if (node == null)
return 0;
int cur = 0;
if (node.val == sum)
cur = 1;
return cur + getSum(node.left, sum-node.val) + getSum(node.right, sum-node.val);
}
}
538. Convert BST to Greater Tree
class Solution {
int sum = 0;
public TreeNode convertBST(TreeNode root) {
convert(root);
return root;
}
public void convert(TreeNode cur){
if (cur == null) return;
convert(cur.right);
cur.val += sum;
sum = cur.val;
convert(cur.left);
}
}
20. Valid Parentheses
public boolean isValid(String s) {
Stack<Character> stack = new Stack<Character>();
for (char c : s.toCharArray()) {
if (c == '(')
stack.push(')');
else if (c == '{')
stack.push('}');
else if (c == '[')
stack.push(']');
else if (stack.isEmpty() || stack.pop() != c)
return false;
}
return stack.isEmpty();
}