leetcode 6. 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:
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

分析过程

  • 题目归类:
    一次填写数组,数学类型。
  • 题目分析:
    把每一个字符按照题目要求的顺序放到新的字符串中
  • 边界分析:
    • 空值分析
      s==null
    • 循环边界分析
  • 方法分析:
    • 数据结构分析
      StringBuilder
      注意使用StringBuilder数组的时候需要进行初始化,生成的只是空壳
    • 状态机
    • 状态转移方程
    • 最优解
  • 测试用例构建
    [];

代码实现

class Solution {
    public String convert(String s, int numRows) {
        if(s== null ||s.length()<=numRows || numRows==1) {
            return s;
        }
        StringBuilder[] sb = new StringBuilder[numRows];
        for(int m = 0 ; m < numRows;m++){
            sb[m] = new StringBuilder();
        }
        int i = 0;
        while(i<s.length()){
            for(int tmp = 0; tmp<numRows&&i<s.length();tmp++){
                sb[tmp].append(s.charAt(i++));
            }
            for(int tmp = numRows-2; tmp>=1&&i<s.length();tmp--) {
                sb[tmp].append(s.charAt(i++));
            }
        }
        String ref = "";
        for(int j = 0;j<numRows;j++){
            ref +=""+sb[j];
        }
        return ref;
    }
}

效率提高

拓展问题

没什么类似的题,这种考的是反应····,掌握基本方法就行了

posted @ 2020-02-11 13:25  clnsx  阅读(100)  评论(0编辑  收藏  举报