6:ZigZag Conversion

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".

 

参考 ZigZag Conversion 思路很清晰

 

String convert(String s, int nRows){
        if(nRows == 1){
            return s;
        }
        
        String [] strs = new String[nRows];
        
        int i=0,j,gap = nRows-2;
        while(i<s.length()){
            for(j=0;j<nRows && i<s.length();j++){
                if(strs[j]==null){
                    strs[j] = "";
                }
                strs[j] += s.charAt(i++);
            }
            for(j=gap;j>0 && i<s.length();j--){
                strs[j] += s.charAt(i++);
            }
        }
        
        String str = "";
        for(String ss : strs){
            str += ss;
        }
        return str;
    }

posted @ 2015-07-13 19:00  shisw  阅读(104)  评论(0编辑  收藏  举报