LeetCode-ZigZag Conversion

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_24133491/article/details/84770124

Description:
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"

Example 2:

Input: s = "PAYPALISHIRING", numRows = 4
Output: "PINALSIGYAHRPI"
Explanation:

P     I    N
A   L S  I G
Y A   H R
P     I

题意:对所给的字符串按照顺序进行行数为numRows的Z字形排列后,按照行的顺序将每行的字符串拼接成一个字符串后返回;

解法:我们可以遍历字符串,将每个字符按照Z字形进行排列,将其放入对应行的字符序列中,这样在遍历完所有的字符后,按照行的顺序将每一行的所有字符序列拼接在一起就得到了最后的结果;

Java
class Solution {
    public String convert(String s, int numRows) {
        if (numRows == 1) return s;
        List<StringBuilder> rows = new ArrayList<>();
        for (int i = 0; i < Math.min(numRows, s.length()); i++) {
            rows.add(new StringBuilder());
        }
        boolean dir = false;
        int row = 0;
        for (char c : s.toCharArray()) {
            rows.get(row).append(c);
            if (row == 0 || row == rows.size() -1) dir = !dir;
            row = dir ? row + 1 : row - 1;
        }
        StringBuilder result = new StringBuilder();
        for (StringBuilder str : rows) result.append(str);
        return result.toString();
    }
}

猜你喜欢

转载自blog.csdn.net/qq_24133491/article/details/84770124