Tuesday, June 3, 2014

LeetCode Integer to Roman

public String intToRoman(int num) {
        int[] numbers = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
        String[] symbols = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};
       
        String result = "";
        int index = 0;
        while (num>0) {
            int times = num / numbers[index];
            num -= numbers[index] * times;
            while (times > 0) {
                result += symbols[index];
                times--;
            }
            index++;
        }
        return result;
    }

LeetCode ConainerWithMostWater

Always moving the smaller side.

public int maxArea(int[] height) {
        int start=0;
        int end=height.length-1;
        int area = 0;
       
        while (start < end) {
            area = Math.max(area, (end - start) * Math.min(height[start], height[end]));
            if (height[start] > height[end]) {
                end--;
            } else {
                start++;
            }
        }
        return area;
    }

Monday, June 2, 2014

LeetCode Regular Expression Match

It always to get the time limited exceed.
Skipping some cases can avoid the situation.

public boolean isMatch(String s, String p) {
        //I have the boundary condition
//although it is easy to follow
   if(s.length()==0)
            return p.length()>1 && p.length()%2==0 ? p.charAt(1)== '*'
                && isMatch(s,p.substring(2)) : p.length()==0;
if (p.isEmpty()) return false;

char c1 = s.charAt(0);
char c2 = p.charAt(0);
char c2next = p.length() > 1 ? p.charAt(1) : 'x';
if (c2next == '*') {
if (isSame(c1,c2)) {
return isMatch(s.substring(1), p) || isMatch(s, p.substring(2));
} else {
return isMatch(s,p.substring(2));
}
} else {
if (isSame(c1,c2)) {
return isMatch(s.substring(1),p.substring(1));
} else {
return false;
}
}

}
private static boolean isSame(char c1, char c2) {
return c2 == '.' || c1==c2;
}

LeetCode Palindrome Number

1. negative is not palindrome number
2. use double to avoid the overflow.

public boolean isPalindrome(int x) {
        if (x < 0) return false;
        if (x == 0) return true;
        double rev = 0;
        int y = x; //don't forget to save the original number before you do some operation.
        while (x != 0) {
            rev = rev * 10 + x%10;
            x /= 10;
        }
        if (rev > Integer.MAX_VALUE) {
            return false;
        }
     
        return (int)rev == y ;
    }

Leetcode atoi

5 conditions need to check
1. null or empty string
2. skip all the white spaces
3. negative and positive sign
4. calculate the value
5. handle the overflow : here we used double type to avoid overflow. It make the code much clear.

    public int atoi(String str) {
        //null or empty string
        if (str == null || str.length() == 0) {
            return 0;
        }
        //skip all the white space
        double result = 0;
        boolean isNegative = false;
        int index = 0;
        while (index < str.length() && str.charAt(index) == ' ') {
            index++;
        }
        //negative and positive sign
        if (str.charAt(index) == '+') {
            isNegative = false;
            index++;
        } else if (str.charAt(index) == '-') {
            isNegative = true;
            index++;
        }
        //calculate the value
        while (index < str.length() && str.charAt(index) >= '0' && str.charAt(index) <= '9') {
            result = result*10 + (str.charAt(index) - '0');
            index++;
        }
        if (isNegative) {
            result = result * (-1);
        }
        //handle the overflow
        if (result > Integer.MAX_VALUE) {
            return Integer.MAX_VALUE;
        }
        if (result < Integer.MIN_VALUE) {
            return Integer.MIN_VALUE;
        }
        return (int)result;
    }

LeetCode LongestPalindrome

Time Complexity is O(n^2) Space Complexity is O(1)
Sorry for not Mancher's algorithm, since it is too complicated for me.

public String longestPalindrome(String s) {
       if (s==null || s.length()==0) return null;
       if (s.length()==1) return s;
     
       String longest = s.substring(0,1);
       for (int i=0; i<s.length(); i++) {
           //Get longest palindrome from the center of i
           String temp = helper(s,i,i);
           if (temp.length() > longest.length()) {
               longest = temp;
           }
           //Get longest palindrome from the center of i, i+1
            temp = helper(s,i,i+1);
           if (temp.length() > longest.length()) {
               longest = temp;
           }
       }
       return longest;
    }
    private String helper(String s, int start, int end) {
        while (start>=0 && end<= s.length()-1&& s.charAt(start) == s.charAt(end)) {
            start--;
            end++;
        }
        return s.substring(start+1, end);
    }

LeetCode ZigZag Conversion

Implimentation:
index+unitsize - 2*row

public String convert(String s, int nRows) {
        //Boundary condition
        if (s==null || s.length()==0 || nRows <=0) return "";
        if (nRows==1) return s;
        //Traverse the whole string, chopped the string as different unit
        //The unit size should be 2*nRows - 2
        //In each unit, the first column is easy to handle.
        //The second column need to use index + Unitsize - 2 * row
        int unitSize = 2*nRows - 2;
        StringBuilder result = new StringBuilder();
        for (int i=0; i<nRows; i++) {
            for (int j = i; j < s.length(); j+=unitSize) {
                result.append(s.charAt(j));
                if (i!=0 && i!=nRows-1 && j+unitSize-2*i<s.length()) {
                    result.append(s.charAt(j+unitSize-2*i));
                }
            }
        }
        return result.toString();
    }