LeetCode 6. ZigZag Conversion

来源:互联网 发布:柯林斯 知乎 编辑:程序博客网 时间:2024/06/11 13:19
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   NA P L S I I GY   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".

转载自 点击打开链接

public class Solution {    public String convert(String s, int numRows) {        char[] ss =s.toCharArray();        if(numRows<=1){            return s;        }else if(numRows>=s.length()){            return s;        }else{            StringBuffer result=new StringBuffer();                       int tap= 2*numRows-2;                        //先添加第一行的字符            for(int i=0;i<s.length();i+=tap){                 result.append(ss[i]);            }            //然后添加中间行            int temp = tap -2;                        for(int i=1;i<numRows-1;i++){                for(int j=i;j<s.length();j+=tap)                {                    result.append(ss[j]);                    if(j+temp<s.length()){                        result.append(ss[j+temp]);                    }                }                temp-=2;            }                        //添加最后一行            for(int i=numRows-1;i<s.length();i+=tap){                result.append(ss[i]);            }            return result.toString();        }            }}