String - 6. ZigZag Conversion

时间:2022-07-25
本文章向大家介绍String - 6. ZigZag Conversion,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
  1. 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 s, int numRows);

Example 1:

Input: s = "PAYPALISHIRING", numRows = 3 Output: "PAHNAPLSIIGYIR"

思路:

遍历字符串,找出拐点,然后记录每一行的字母,最后把每一行字母拼接起来。

代码:

java:

class Solution {

    public String convert(String s, int numRows) {

        if (s == null || s.length() == 0) return "";
        if(numRows < 2)   return s;
        
        int len = s.length();

        StringBuilder[] sbs = new StringBuilder[numRows];
        for (int i = 0; i < numRows; i++) sbs[i] = new StringBuilder();
        
        char[] strs = s.toCharArray();
        for (int i = 0; i < strs.length;) {
            for (int row = 0; i < strs.length && row < numRows; row++) {
                sbs[row].append(strs[i++]);
            }
            for (int row = numRows - 2; i < strs.length && row > 0; row--) {
                sbs[row].append(strs[i++]);
            }      
        }
        
        for (int i = 1; i < numRows; i++) {
            sbs[0].append(sbs[i]);
        }
        
        return sbs[0].toString();
    }
}