Personal Leetcode solution(Java)36-40
Valid Number
Core: Regular, Test Case
public class ValidNumber { public boolean isNumber(String s) { s = s.trim(); //Match decimal as +- XXX.XXX if(s.matches("(-?|\\+?)((\\d+)?\\.\\d+|\\d+\\.(\\d+)?)")) return true; //Match scientific notation if(s.matches("(-?|\\+?)(\\d+\\.(\\d+)?|(\\d+)?\\.\\d+|\\d+)[e](-?|\\+?)\\d+")) return true; //Match simple number if(s.matches("(-?|\\+?)\\d+")) return true; return false; } }
WordLadderII
Core: Use BFS to find the shortest distance between start and end, Use DFS to output paths with the same distance as the shortest distance
Reference: https://discuss.leetcode.com/topic/27504/my-concise-java-solution-based-on-bfs-and-dfs
import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Queue; import java.util.Set; public class WordLadderII { public List<List<String>> findLadders(String beginWord, String endWord, Set<String> wordList) { List<List<String>> res = new ArrayList<List<String>>(); //Neighbours for every node HashMap<String, ArrayList<String>> nodeNeighbors = new HashMap<String, ArrayList<String>>(); //Distance of every node from the start node HashMap<String, Integer> distance = new HashMap<String,Integer>(); ArrayList<String> solution = new ArrayList<String>(); wordList.add(endWord); bfs(beginWord, endWord, wordList, nodeNeighbors, distance); dfs(beginWord, endWord, wordList, nodeNeighbors, distance, solution, res); return res; } /**BFS: Trace every node's distance from the start node(level by level) * @param start the start word * @param end the end word * @param wordlist all wordList could be included in the tree * @param nodeNeghbors HashMap to save possible next node for each word * @param distance HashMap to save distance from start to node for each word */ private void bfs(String start, String end, Set<String> wordlist, HashMap<String, ArrayList<String>> nodeNeghbors, HashMap<String, Integer> distance){ for (String string : wordlist) { nodeNeghbors.put(string, new ArrayList<String>()); } Queue<String> queue = new LinkedList<String>(); queue.offer(start); distance.put(start, 0); while(!queue.isEmpty()){ int count = queue.size(); boolean foundEnd = false; for(int i = 0; i<count;i++){ String cur = queue.poll(); int curdistance = distance.get(cur); //get all next level node for the value in the queue ArrayList<String> neighbours = getNextneightbours(cur, wordlist); //calculate the distance of node in the queue for (String string : neighbours) { nodeNeghbors.get(cur).add(string); if(!distance.containsKey(string)){ // check this word is visited or not distance.put(string, curdistance+1); //check the next level include end or not if(end.equals(string)) foundEnd = true; else queue.offer(string); } } } if(foundEnd) break; } } /** * Find all next level nodes * @param node the input node which need to find next level nodes * @param wordlist the translate wordList * @return all next level nodes */ private ArrayList<String> getNextneightbours(String node, Set<String> wordlist){ ArrayList<String> res = new ArrayList<String>(); char chs[] = node.toCharArray(); for(char ch = 'a'; ch <= 'z'; ch++){ for(int i =0;i<chs.length;i++){ if(chs[i] == ch) continue; char old_ch = chs[i]; chs[i] = ch; if(wordlist.contains(String.valueOf(chs))) res.add(String.valueOf(chs)); chs[i] = old_ch; } } return res; } /** * DFS: Output all paths with the shortest distance. * @param cur current word * @param end end word * @param wordList all wordList could be included in the tree * @param nodeNeghbors HashMap to save possible next node for each word * @param distance HashMap to save distance from start to node for each word * @param solution the solution for the question * @param res all solutions */ private void dfs(String cur, String end, Set<String> wordList, HashMap<String, ArrayList<String>> nodeNeghbors, HashMap<String, Integer> distance, ArrayList<String> solution, List<List<String>> res){ solution.add(cur); if(end.equals(cur)){ res.add(new ArrayList<String>(solution)); } else{ for (String next : nodeNeghbors.get(cur)) { if(distance.get(next) == distance.get(cur)+1) dfs(next, end, wordList, nodeNeghbors, distance, solution, res); } } solution.remove(solution.size() -1); } }
Max Points on a Line
Core: use "Slope" to show each point in map for each point. time complexity of this algorithm is O(n2)
/** * Definition for a point. * class Point { * int x; * int y; * Point() { x = 0; y = 0; } * Point(int a, int b) { x = a; y = b; } * } */ import java.util.HashMap; public class Solution { public int maxPoints(Point[] points) { if(points.length<=1) return points.length; int max = 0; for(int i =0;i<points.length;i++){ HashMap<Double, Integer> map = new HashMap<Double, Integer>(); int sameX =1, sameP =0; for(int j =0;j<points.length;j++){ if(j != i){ if((points[j].x == points[i].x && points[j].y == points[i].y)) sameP++; if(points[j].x == points[i].x){ sameX++; continue; } double k = (double)(points[j].y - points[i].y) / (double)(points[j].x - points[i].x); if(map.containsKey(k)){ map.put(k, map.get(k)+1); } else map.put(k, 2); max = Math.max(map.get(k)+sameP, max); } max = Math.max(sameX, max); } } return max; } }
LRUCache
Core:
Double enter linked list with the value called “key”, all data saved in another HashMap.
New data would be inserted after head, if over capacity, remove the last one in the linked list
linked list is a list sorted by recently used.
import java.util.HashMap; public class LRUCache { private HashMap<Integer, DLinkedNode> cache = new HashMap<Integer,DLinkedNode>(); private int count; private int capacity; private DLinkedNode head,tail; public LRUCache(int capacity){ this.capacity = capacity; this.count = 0; head = new DLinkedNode(); head.pre = null; tail = new DLinkedNode(); head.post = tail; tail.pre = head; } /** * return the value of node assigned with key and move the node to the position after head * @param key the key assign the node * @return the value of key */ public int get(int key){ DLinkedNode node = cache.get(key); if(node == null){ return -1; } else { moveToHead(node); return node.value; } } /** * insert or set a new node, if over capacity, remove the last one in the linked list * @param key the key of node would be set * @param value the value of this node */ public void set(int key, int value) { DLinkedNode node = cache.get(key); if(node == null){ DLinkedNode newNode = new DLinkedNode(); newNode.key = key; newNode.value = value; this.cache.put(key, newNode); this.addNode(newNode); ++count; if(count > capacity){ // pop the tail DLinkedNode tail = this.popTail(); this.cache.remove(tail.key); --count; } }else{ // update the value. node.value = value; this.moveToHead(node); } } /** * add node after head * @param node the node would be added after head */ private void addNode(DLinkedNode node){ node.pre = head; node.post = head.post; head.post.pre = node; head.post = node; } /** * remove an existing node from the linked list * @param node the node would be removed */ private void removeNode(DLinkedNode node){ DLinkedNode pre = node.pre; DLinkedNode post = node.post; pre.post = post; post.pre = pre; } /** * move certain node in between to the position after head * @param node the node need to be moved */ private void moveToHead(DLinkedNode node){ this.removeNode(node); this.addNode(node); } /** * pop the current tail * @return the node would be pop */ private DLinkedNode popTail(){ DLinkedNode res = tail.pre; this.removeNode(res); return res; } } class DLinkedNode { int key; int value; DLinkedNode pre; DLinkedNode post; }
TextJustification
import java.util.ArrayList; import java.util.List; public class TextJustification { public List<String> fullJustify(String[] words, int maxWidth) { if (words == null) return new ArrayList<>(); List<String> j = new ArrayList<>(); int l = words.length, currLen = 0; List<String> currLine = new ArrayList<>(); // Process each word for (int i = 0; i < l; i++) { // Check if we can accommodate more words if (currLen + words[i].length() <= maxWidth) { currLine.add(words[i]); currLine.add(" "); // add spaces between words, we will deal with the last space later. currLen += words[i].length() + 1; } else { // We have exhausted the max length currLen--; currLine.remove(currLine.size() - 1); // trim the last space as we need right justification insertWS(currLine, maxWidth - currLen); // insert white spaces j.add(printLine(currLine)); // convert the current line from list to a string and add to the justified list. currLine = new ArrayList<>(); // re initialise the current line to begin a new line. currLen = 0; i--; } } // This is the last line if (!currLine.isEmpty()) { currLen--; currLine.remove(currLine.size() - 1); insertWSLastLine(currLine, maxWidth - currLen); j.add(printLine(currLine)); } return j; } // spread spaces evenly in the list public void insertWS(List<String> line, int n) { int l = line.size(); if (l == 1) insertWSLastLine(line, n); else { for (int i = 0, j = 0; i < n;) { if (line.get(j).trim().isEmpty()) { i++; line.set(j, line.get(j) + " "); } if (j == l - 1) { j = 0; } else { j++; } } } } // Keep appending spaces to the end of the list. public void insertWSLastLine(List<String> line, int n) { for (int i = 0; i < n; i++) { line.add(" "); } } // convert list to a string. public String printLine(List<String> line) { String str = ""; for (String s : line) { str += s; } return str; } }
浙公网安备 33010602011771号