lintcode做题总结, Oct 31 A

1. Different Ways to Add Parentheses 所有不同加括号的可能性,这种题应该可以直接想到递归


public class Solution {
    private int compute(String s) {
            //System.out.println(s);
            for (int i = 1; i < s.length(); i++) {
                if (s.charAt(i) == '+') {
                    return Integer.parseInt(s.substring(0, i)) + Integer.parseInt(s.substring(i + 1));
                } else if (s.charAt(i) == '-') {
                    return Integer.parseInt(s.substring(0, i)) - Integer.parseInt(s.substring(i + 1));
                } else if (s.charAt(i) == '*'){
                    return Integer.parseInt(s.substring(0, i)) * Integer.parseInt(s.substring(i + 1));
                }
            }
            return 0;
        }
    public List<Integer> diffWaysToCompute(String input) {
        
        ArrayList<Integer> res = new ArrayList<Integer>();
        try{
            res.add(Integer.parseInt(input));
            return res;
        } catch (Exception e) {
            
        }
        
        for (int i = 1; i < input.length(); i++) {
                if(input.charAt(i) == '+' || input.charAt(i) == '-' || input.charAt(i) == '*') {
                    List<Integer> l = diffWaysToCompute(input.substring(0, i));
                    List<Integer> r = diffWaysToCompute(input.substring(i + 1));
                    for (Integer lnum : l){
                        for (Integer rnum : r) {
                            res.add(
                                    compute(
                                            lnum + input.substring(i, i + 1) + rnum
                                    ));
                        }
                    }
                    
                }
            }
        return res;
        
    }
    
}

2. Add Digits 循环即可

public class Solution {
    public int addDigits(int num) {
        String nums = String.valueOf(num);
        while (nums.length() > 1) {
            int sum = nums.charAt(nums.length() - 1) - '0';
            for (int i = nums.length() - 2; i >= 0; i--) {
                sum += (nums.charAt(i) - '0');
            }
            nums = String.valueOf(sum);
        }
        
        return Integer.parseInt(nums);
        
    }
}

3. Word Pattern 用hashmap对应判断即可

public class Solution {
    public boolean wordPattern(String pattern, String str) {
        HashMap<Character, String> map = new HashMap<Character, String>();
        String[] strArr = str.split(" ");
        if (strArr.length != pattern.length()) {
            return false;
        }
        for (int i = 0; i < pattern.length(); i++) {
            char c = pattern.charAt(i);
            if (map.containsKey(c)) {
                if (strArr[i].equals(map.get(c))) {
                    continue;
                } else {
                    return false;
                }
            } else {
                if (map.containsValue(strArr[i])) {
                    return false;
                }
                map.put(c, strArr[i]);
            }
        }
        return true;
        
    }
}

4. LRU Cache 自己使用node建队列的解法和使用linkedhashmap的解法

import java.util.*;
public class LRUCache {
    /*private class Node {
    	int key;
    	int val;
    	Node pre = null;
    	Node next = null;
    	Node (int key, int val) {
    		this.key = key;
    	    this.val = val;
        }
    }

    HashMap<Integer, Node> map = new HashMap<Integer, Node>();
    int capacity = 0;
    Node head = new Node(0, 0);
    Node end = new Node(0, 0);
    
       
    public LRUCache(int capacity) {
        this.capacity = capacity;
        head.next = end;
    
    }
        
    public int get(int key) {
     	if (map.containsKey(key)) {
    		Node n = map.get(key);
    		remove(n);
    		addHead(n);
    		return n.val;
        } else {
            return -1;
        }
    }
        
    public void set(int key, int value) {
    	if (map.containsKey(key)) {
        	Node n = map.get(key);
        	n.val = value;
        	remove(n);
        	addHead(n);
        } else {
        	if (map.size() == this.capacity) {
            	Node last = end.pre;
                remove(last);
                map.remove(last.key);
            }
            Node n = new Node(key, value);
            addHead(n);
            map.put(key, n);
        }
        		
    }
        
    private void remove (Node n) {
        	
        n.pre.next = n.next;
        n.next.pre = n.pre;
        
        
    }
        
    private void addHead (Node n) {
        if (head.next == end) {
        		head.next = n;
        		n.pre = head;
        		n.next = end;
        		end.pre = n;
        } else {
        	n.next = head.next;
            head.next = n;
            n.pre = head;
            n.next.pre = n;
        
        }
    	
    }*/
    private class Cache extends LinkedHashMap {
    	private int cap;
    	Cache(int cap) {
    	    super(cap, 1.1f,true);
    	    this.cap = cap;
    	}
    	@Override
    	protected boolean removeEldestEntry(Map.Entry E) {
    	    return size() > cap;
    	}
    }

    LinkedHashMap<Integer, Integer> ca;
    int capacity;
    
       
    public LRUCache(int capacity) {
        this.capacity = capacity;
        this.ca = new LinkedHashMap<Integer, Integer>(capacity, 0.75f,true) {
            @Override
            protected boolean removeEldestEntry(Map.Entry<Integer, Integer> e){
                return size() > capacity;
            }
        };
    
    }
        
    public int get(int key) {
        if (!this.ca.containsKey(key)) {
            return -1;
        }
     	return this.ca.get(key);
    }
        
    public void set(int key, int value) {
    	this.ca.put(key, value);
        		
    }
}

5. Find Median from Data Stream, 使用双堆即可,注意堆为空的情况

class MedianFinder {
    PriorityQueue<Integer> pmin = new PriorityQueue<Integer>(new Comparator<Integer>(){
        public int compare(Integer n1, Integer n2){
            return Integer.compare(n1, n2);
        }
        
    });
    PriorityQueue<Integer> pmax = new PriorityQueue<Integer>(new Comparator<Integer>(){
        public int compare(Integer n1, Integer n2){
            return Integer.compare(n2, n1);
        }
        
    });
    // Adds a number into the data structure.
    public void addNum(int num) {
        if (pmax.size() == 0 || pmin.size() == 0){
            pmax.add(num);
        }
        if (pmin.size() != 0 && pmax.size() != 0){
            double mid = findMedian();
            if ((double)num >= mid) {
                pmin.add(num);
            } else {
                pmax.add(num);
            }
        }
        while (pmax.size() - pmin.size() > 1) {
            pmin.add(pmax.poll());
        }
        while (pmin.size() - pmax.size() > 1) {
            pmax.add(pmin.poll());
        }
    }

    // Returns the median of current data stream
    public double findMedian() {
        if (pmin.size() != 0 && pmax.size() != 0) {
            if (pmin.size() == pmax.size()) {
                return (pmin.peek() + pmax.peek()) / 2.0;
            } else if (pmin.size() > pmax.size()) {
                return (double)pmin.peek();
            } else {
                return (double)pmax.peek();
            }
        }
        if (pmin.size() != 0) {
            return pmin.peek();
        }
        if (pmax.size() != 0) {
            return pmax.peek();
        }
        return 0.0;
    }
};

// Your MedianFinder object will be instantiated and called as such:
// MedianFinder mf = new MedianFinder();
// mf.addNum(1);
// mf.findMedian();

6. Implement Trie (Prefix Tree) 注意add和search的时候都是使用一个公园的map curr然后不停的更新即可

class TrieNode {
    // Initialize your data structure here.
    char c;
    HashMap<Character, TrieNode> children = new HashMap<Character, TrieNode>();
    boolean isLeaf;
    public TrieNode(char c) {
        this.c = c;
    }
    public TrieNode() {
    }
}

public class Trie {
    private TrieNode root;

    public Trie() {
        root = new TrieNode();
    }

    // Inserts a word into the trie.
    public void insert(String word) {
        HashMap<Character, TrieNode> children = root.children;
 
        for(int i = 0; i < word.length(); i++){
            char c = word.charAt(i);
 
            TrieNode t;
            if(children.containsKey(c)){
                    t = children.get(c);
            }else{
                t = new TrieNode(c);
                children.put(c, t);
            }
 
            children = t.children;
 
            //set leaf node
            if(i == word.length() - 1)
                t.isLeaf = true;    
        }
    }
 
    // Returns if the word is in the trie.
    public boolean search(String word) {
        TrieNode t = searchNode(word);
 
        if(t != null && t.isLeaf) 
            return true;
        else
            return false;
    }
 
    // Returns if there is any word in the trie
    // that starts with the given prefix.
    public boolean startsWith(String prefix) {
        if(searchNode(prefix) == null) 
            return false;
        else
            return true;
    }
 
    public TrieNode searchNode(String str){
        Map<Character, TrieNode> children = root.children; 
        TrieNode t = null;
        for(int i = 0; i < str.length(); i++){
            char c = str.charAt(i);
            if(children.containsKey(c)){
                t = children.get(c);
                children = t.children;
            }else{
                return null;
            }
        }
 
        return t;
    }
}

// Your Trie object will be instantiated and called as such:
// Trie trie = new Trie();
// trie.insert("somestring");
// trie.search("key");

7. Word Search II 每添加一个char历遍一次trie

class Trie {
    class TrieNode {
        char c;
        boolean isEnd = false;
        HashMap<Character, TrieNode> m = new HashMap<Character, TrieNode>();
        TrieNode (char c) {
            this.c = c;
        }
        TrieNode () {}
    }
    HashMap<Character, TrieNode> m = new HashMap<Character, TrieNode>();
    public void insert(String word) {
        HashMap<Character, TrieNode> curr = m;
        TrieNode node = null;
        for (int i = 0; i < word.length(); i++) {
            char c = word.charAt(i);
            if (!curr.containsKey(c)) {
                node = new TrieNode(c);
                curr.put(c, node);
            } else {
                node = curr.get(c);
            }
            curr = node.m;
        }
        if (node != null)
            node.isEnd = true;
    }
    public int search(String word) {
        HashMap<Character, TrieNode> curr = m;
        TrieNode node = null;
        for (int i = 0; i < word.length(); i++) {
            char c = word.charAt(i);
            if (!curr.containsKey(c)) {
                return -1;
            } else {
                node = curr.get(c);
            }
            curr = node.m;
        }
        if (node != null && node.isEnd == true) {
            return 1;
        }
        return 0;
        
    }
    
}
public class Solution {
    private void dfs(char[][] board, String word, int i, int j, ArrayList<String> res, Trie t) {
        if (i < 0 || i >= board.length || j < 0 || j >= board[0].length) {
            return;
        }
        word = word + board[i][j];
        int status = t.search(word);
        if (status == -1) {
            return;
        }
        if (status == 1) {
            if (!res.contains(word))
                res.add(word);
        }
        char tmp = board[i][j];
        board[i][j] = '%';
        dfs(board, word, i - 1, j, res, t);
        dfs(board, word, i + 1, j, res, t);
        dfs(board, word, i, j - 1, res, t);
        dfs(board, word, i, j + 1, res, t);
        board[i][j] = tmp;
    }
    
    public List<String> findWords(char[][] board, String[] words) {
        ArrayList<String> res = new ArrayList<String>();
        if (board.length == 0 || words.length == 0) {
            return res;
        }
        Trie t = new Trie();
        for (String word : words) {
            t.insert(word);
        }
        
        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[0].length; j++){
                dfs(board, "", i, j, res, t);
            }
        }
        
        
        return res;
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值