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

问题分析

这题属于找规律的题目,只要弄懂Z型走位的规律就行了。不过很容易出错。

代码实现

public String convert(String s, int nRows) {
        if (s.length() < 0 || s.length() < nRows) return s;
        StringBuilder[] stringBuilders = new StringBuilder[nRows];
        for (int i = 0; i < nRows; i++) {
            stringBuilders[i] = new StringBuilder();
        }
        char[] c = s.toCharArray();
        int index = 0;
        while (index < s.length()) {
            for (int i = 0; i < nRows && index < s.length(); i++) {
                stringBuilders[i].append(c[index]);
                index++;
            }
            for (int i = nRows - 2; i > 0 && index < s.length(); i--) {
                stringBuilders[i].append(c[index]);
                index++;
            }
        }
        for (int i = 1; i < nRows; i++) {
            stringBuilders[0].append(stringBuilders[i]);
        }
        return stringBuilders[0].toString();
    }

你可能感兴趣的:(LeetCode每日一题:zigzag conversion)