6. ZigZag Conversion 【Medium】

avatar 2020年08月30日17:49:13 6 1964 views
博主分享免费Java教学视频,B站账号:Java刘哥

Question

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

 

My Answer

class Solution {
     public String convert(String s, int numRows) {
        if (numRows <= 1) {
            return s;
        }

        // 初始化
        StringBuilder[] sb = new StringBuilder[numRows];
        for (int i = 0; i < numRows; i++) {
            sb[i] = new StringBuilder("");
        }

        // 遍历数据,写入sb中
        // true向下走,false向上走
        boolean flag = true;
        int index = 0;
        for (int i = 0; i < s.length(); i++) {
            sb[index].append(s.charAt(i));

            // 从第一行,向下走
            if (index == 0) {
                flag = true;
            }
            // 最后一行,往上走
            if (index == numRows - 1) {
                flag = false;
            }
            
            if (flag) {
                index++;
            } else {
                index--;
            }
        }

        // 组装
        StringBuilder result = new StringBuilder("");
        for (StringBuilder temp : sb) {
            result.append(temp);
        }

        return result.toString();
    }
}

 

 

  • 微信
  • 交流学习,有偿服务
  • weinxin
  • 博客/Java交流群
  • 资源分享,问题解决,技术交流。群号:590480292
  • weinxin
avatar

发表评论

avatar 登录者:匿名
匿名评论,评论回复后会有邮件通知

  

已通过评论:0   待审核评论数:0