[Leetcode] 6. ZigZag Conversion

来源:互联网 发布:4g网络覆盖城市 编辑:程序博客网 时间:2024/05/06 13:55

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 nRows) {        if(s == null || s.length() <= 1 || nRows <= 1) return s;        int size = 2 * nRows - 2;        StringBuffer result = new StringBuffer();        for(int i = 0; i < nRows; i++){            for(int j = i; j < s.length(); j += size){                result.append(s.charAt(j));                if(i != 0 && i != nRows - 1 && j + size - 2 * i < s.length()){                    result.append(s.charAt(j + size - 2 * i));                }            }        }        return result.toString();    }}


0 0
原创粉丝点击