leetcode刷题整理-用java做的题

JAVA一些语法整理:

Queue:

Queue queue = new LinkedList();
queue.offer("a");  //  添加一个元素并返回true 
queue.poll();  // get and pop the first element
queue.peek();  // 返回队列头部的元素    

Stack:

Stack stack = new Stack();
stack.push(root);
stack.pop();
stack.peek(); // 查看最后一个元素,但不删除
stack.empty(); // 返回bollean

LinkedList:

List res = new LinkedList<>();
res.toArray(new String[0]);  // 转array
res.remove(0); // 按位置删除

ArrayList:

     List list=new ArrayList();
     list.add("Hello");

     ArrayList list = new ArrayList();

数组:

int list[] = {1, 2, 3};

		for(int i=0; i < re.length; i++) {
			System.err.println(re[i]);
		}

 

===================================

500. Keyboard Row

leetcode刷题整理-用java做的题_第1张图片

class Solution {
    public String[] findWords(String[] words) {
        String[] strs = {"QWERTYUIOP","ASDFGHJKL","ZXCVBNM"};
        Map map = new HashMap<>();
        for (int i=0; i < strs.length; i++){
            for (char c: strs[i].toCharArray()){
                map.put(c, i);
            }
        }
        List 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

leetcode刷题整理-用java做的题_第2张图片

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

leetcode刷题整理-用java做的题_第3张图片

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

leetcode刷题整理-用java做的题_第4张图片

public boolean isValid(String s) {
	Stack stack = new Stack();
	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();
}

 

你可能感兴趣的:(java,Algorithm)