6/22/2014

151. Max Points on a Line

/**
 * Definition for a point.
 * class Point {
 *     int x;
 *     int y;
 *     Point() { x = 0; y = 0; }
 *     Point(int a, int b) { x = a; y = b; }
 * }
 */
public class Solution {
    public int maxPoints(Point[] points) {
        if (points == null || points.length == 0) {
            return 0;
        }

        HashMap<Double, Integer> map=new HashMap<Double, Integer>();
        int max = 1;

        for(int i = 0 ; i < points.length; i++) {
            // shared point changed, map should be cleared and server the new point
            map.clear();

            // maybe all points contained in the list are same points,and same points' k is
            // represented by Integer.MIN_VALUE
            map.put((double)Integer.MIN_VALUE, 1);

            int dup = 0;
            for(int j = i + 1; j < points.length; j++) {
                if (points[j].x == points[i].x && points[j].y == points[i].y) {
                    dup++;
                    continue;
                }

                // look 0.0+(double)(points[j].y-points[i].y)/(double)(points[j].x-points[i].x)
                // because (double)0/-1 is -0.0, so we should use 0.0+-0.0=0.0 to solve 0.0 !=-0.0
                // problem

                // if the line through two points are parallel to y coordinator, then K(slop) is
                // Integer.MAX_VALUE
                double key=points[j].x - points[i].x == 0 ?
                    Integer.MAX_VALUE :
                    0.0 + (double)(points[j].y - points[i].y) / (double)(points[j].x - points[i].x);

                if (map.containsKey(key)) {
                    map.put(key, map.get(key) + 1);
                } else {
                    map.put(key, 2);
                }
            }

            for (int temp: map.values()) {
                // duplicate may exist
                if (temp + dup > max) {
                    max = temp + dup;
                }
            }

        }
        return max;
    }
}

150. Word Ladder II

public class Solution {
    public ArrayList<ArrayList<String>> findLadders(String start, String end, Set<String> dict) {

dict.add(end);

// Key: the dictionary string; Value: HashSet<ArrayList<String>>
Map<String, HashSet<ArrayList<String>>> map = new HashMap<String, HashSet<ArrayList<String>>>();
Queue<String> queue = new LinkedList<String>();

ArrayList<String> startPath = new ArrayList<String>();
startPath.add(start);
HashSet<ArrayList<String>> startSet = new HashSet<ArrayList<String>>();
startSet.add(startPath);
queue.offer(start);
map.put(start, startSet);

ArrayList<ArrayList<String>> ret = new ArrayList<ArrayList<String>>();

while (!queue.isEmpty()) {
String str = queue.poll();

if (str.equals(end)) {
ret.addAll(map.get(end));
return ret;
}

for (int i = 0; i < str.length(); i++) {
for (int j = 0; j <= 25; j++) {
// transform it into another word
String newStr = replace(str, i, (char) ('a' + j));

// if a new word is explored
if (dict.contains(newStr)) {
if (!map.containsKey(newStr)) {
// construct a new path set
HashSet<ArrayList<String>> prevSet = map.get(str);
HashSet<ArrayList<String>> newSet = new HashSet<ArrayList<String>>();
for (ArrayList<String> path : prevSet) {
ArrayList<String> newPath = new ArrayList<String>(path);
newPath.add(newStr);
newSet.add(newPath);
}

map.put(newStr, newSet);
queue.offer(newStr);
} else {
HashSet<ArrayList<String>> prevSet = map.get(str);
HashSet<ArrayList<String>> newSet = map.get(newStr);

Iterator<ArrayList<String>> prevIt = prevSet
.iterator();
Iterator<ArrayList<String>> newIt = newSet
.iterator();

// increase the path set
if (prevIt.next().size() + 1 == newIt.next().size()) {
for (ArrayList<String> path : prevSet) {
ArrayList<String> newPath = new ArrayList<String>(path);
newPath.add(newStr);
newSet.add(newPath);
// queue.offer(newStr); // will cause TLE!!!
}
}
}
}
}
}
}

return ret; // return an empty set
}

// replace the index of the given string with the given char
private String replace(String str, int index, char c) {
StringBuilder sb = new StringBuilder(str);
sb.setCharAt(index, c);
return sb.toString();
}
}

149. Valid Number

public class Solution {
    public boolean isNumber(String s) {
        int len = s.length();
     
        int i = 0, e = len - 1;
        while (i <= e && Character.isWhitespace(s.charAt(i))) i++;
        if (i > len - 1) return false;
        while (e >= i && Character.isWhitespace(s.charAt(e))) e--;
     
        // skip leading +/-
        if (s.charAt(i) == '+' || s.charAt(i) == '-') i++;
        boolean num = false; // is a digit
        boolean dot = false; // is a '.'
        boolean exp = false; // is a 'e'
     
        while (i <= e) {
            char c = s.charAt(i);
            if (Character.isDigit(c)) {
                num = true;
            }
            else if (c == '.') {
                if(exp || dot) return false;
                dot = true;
            }
            else if (c == 'e') {
                if(exp || num == false) return false;
                exp = true;
                num = false;
            }
            else if (c == '+' || c == '-') {
                if (s.charAt(i - 1) != 'e') return false;
            }
            else {
                return false;
            }
            i++;
        }
        return num;
    }
}

148. Wildcard Matching

public class Solution {
    public boolean isMatch(String s, String p) {
        int i = 0;
        int j = 0;
        int star = -1;
        int mark = -1;
        while (i < s.length()) {
            if (j < p.length()
                    && (p.charAt(j) == '?' || p.charAt(j) == s.charAt(i))) {
                i++;
                j++;
            } else if (j < p.length() && p.charAt(j) == '*') {
                star = j++;
                mark = i;
            } else if (star != -1) {
                j = star + 1;
                i = ++mark;
            } else {
                return false;
            }
        }
        while (j < p.length() && p.charAt(j) == '*') {
            j++;
        }
        return j == p.length();
    }
}

147. LRU Cache

import java.util.LinkedHashMap;

public class LRUCache {
   
    LinkedHashMap<Integer, Integer> map;
int capacity;
   
    public LRUCache(int capacity) {
        map = new LinkedHashMap<Integer, Integer> (capacity);
   this.capacity = capacity;
    }
   
    public int get(int key) {
        if(map.containsKey(key)){
            int val = map.get(key);
       map.remove(key);
       map.put(key, val);
       return val;
        }
        return -1;
    }
   
    public void set(int key, int value) {
        if(map.containsKey(key)){
            map.remove(key);
            map.put(key, value);
        }else{
            if(map.size() == capacity){
                int firstKey = map.keySet().iterator().next();
                map.remove(firstKey);
            }
            map.put(key, value);
        }
    }
}

146. Surrounded Regions

public class Solution {
    private Queue<Integer> queue = new LinkedList<Integer>();
   
    public void solve(char[][] board) {
        if (board.length == 0 || board[0].length == 0) return;
       
        int row = board.length;
        int col = board[0].length;

        for (int j = 0; j < col; j++) {
            if (board[0][j] == 'O') bfs(board, 0, j);
        }

        for (int j = 0; j < col; j++) {
            if (board[row - 1][j] == 'O') bfs(board, row - 1, j);
        }

        for (int i = 0; i < row; i++) {
            if (board[i][0] == 'O') bfs(board, i, 0);
        }

        for (int i = 0; i < row; i++) {
            if (board[i][col - 1] == 'O') bfs(board, i, col - 1);
        }

        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
                if (board[i][j] == 'O') board[i][j] = 'X';
                if (board[i][j] == 'P') board[i][j] = 'O';
            }
        }
    }
   
    public void bfs(char[][] board, int i, int j) {
        int col = board[0].length;

        fill(board, i, j);
       
        while (!queue.isEmpty()) {
            int cur = queue.poll();
            int x = cur / col;
            int y = cur % col;

            fill(board, x - 1, y);
            fill(board, x + 1, y);
            fill(board, x, y - 1);
            fill(board, x, y + 1);
        }
    }
   
    public void fill(char[][] board, int i, int j) {
        int row = board.length;
        int col = board[0].length;
       
        if (i < 0 || i >= row || j < 0 || j >= col || board[i][j] != 'O') return;

        queue.offer(i * col + j);
        board[i][j] = 'P';
    }
}

145. Reverse Words in a String

public class Solution {
    public String reverseWords(String s) {
        if (s == null || s.length() == 0) {
            return "";
        }

        String[] array = s.split(" ");
        StringBuilder sb = new StringBuilder();

        for (int i = array.length - 1; i >= 0; i--) {
            if (!array[i].equals("")) {
                sb.append(array[i]).append(" ");
            }
        }

        //remove the last " "
        return sb.length() == 0 ? "" : sb.substring(0, sb.length() - 1);
    }
}