leetcode刷題整理-用java做的題

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

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章