Saturday, March 19, 2016

LeetCode 刷题第一阶段 ZigZag Conversion

The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)
P   A   H   N
A P L S I I G
Y   I   R
And then read line by line: "PAHNAPLSIIGYIR"
Write the code that will take a string and make this conversion given a number of rows:
string convert(string text, int nRows);
convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR".

第一个考虑的问题是如果 nRows 比 input长度还小怎么办 (极端情况是负数)。保险起见还是先check condition.
总体思路的话, 我用了两个Int 当指针。 一个指示正常规律的跳跃一个指示zigzag。 设置了一个常数代表跳跃变量。 注意的问题是当跳跃变量等于0时容易死循环。。。
CODE:
public class Solution {
    public String convert(String s, int numRows) {
        String ret = "" ;
        int len = s.length() ;
        int c = 2 * numRows - 2 ; 
        
        if(c != 0 && 0 < numRows && numRows < len){
            
        for(int i = 0; i < numRows ; i++){
            ret += s.charAt(i);
            int index = i + c ;
            int zig =  c - i ;
            while(index < len || zig < len){
            if(i != 0 && i != (numRows -1)){
                ret += s.charAt(zig);
            }
            if(index < len) ret += s.charAt(index);
            zig += c ;
            index += c ;
            }
        }
        
        } else{
            ret = s;
        }
        
        return ret;
    }

}

LeetCode 刷题第一阶段 Inverse Integer

之前混乱地刷了一些 LeetCode 的题目, 经大神提点,现今决定进入系统刷题。第一阶段是 自主快速刷完所有easy难度的题。之后的阶段求最优解加上进阶medium, hard。


2016. 3. 19
inverse integer:
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321

consideration:
思路比较简单直接,但是博主考虑到restore x 的问题, 然而网上大家都没有考虑相应问题, 题目也没有要求restore 故此处不管。 具体面试的时候可以问考官。
***** 但是要考虑overflow 问题。
The input can be in int range but the output might overflow , for example, if you input (INT_MAX-1), the output will be out of range.
Till now, two solutions for it.
1. Change return answer to long type
2. set upper bound and lower bound to detect 


talk is cheap, show the code :
public class Solution {
    public int reverse(int x) {
        int res = 0;
        while(x != 0){
            int lastD = x % 10 ;
            int upBound = (Integer.MAX_VALUE - lastD) / 10 ;
            int loBound = (Integer.MIN_VALUE - lastD) / 10 ;
            
            if (x>0 && res > upBound) return 0;
            if (x<0 && res < loBound) return 0;

            x = x / 10 ;
            res = res * 10 + lastD ; 
        }
      
        return res;
    }
}

btw 这题也可以用recursion 做 就不写了这次。 因为overflow问题 耽误时间较长希望下次改进。