2014年4月7日 星期一

[LeetCode] ZigZag Conversion

Problems:
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".
Solution:O(n)



public class Solution {
    public String convert(String s, int nRows) {
	if(s == null || s.length()==0 )
            return "";
        if(nRows == 1)
            return s;
        int bsize = 2* nRows-2;
        String ret = "";
        char set[] = s.toCharArray();
        int bb = s.length()/bsize;
        if(s.length() % bsize !=0)
        	bb+=1;
        
        for(int i=0; i<nRows;i++){
            for(int t=0; t< bb;t++){
                if(t*bsize+i >= set.length)
                    break;
                    int index = t*bsize+i;
                    ret += set[index]; 
                    
                if(i != 0 && i != (nRows-1)){
                	int rindex = bsize*(2*t+1) - index;
                	if(rindex <set.length)
                		ret += set[rindex];
                }    
            }
        }
        return ret;
    }
}
Note: The concept is to find the regularity about the sequence.

沒有留言:

張貼留言