leetcode(4)

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”
Example 2:

Input: s = “PAYPALISHIRING”, numRows = 4
Output: “PINALSIGYAHRPI”
Explanation:

P I N
A L S I G
Y A H R
P I
和很多人一样,刚看题目并不知道说的是什么。
其实这道题就是要根据锯齿状遍历一个字符串
leetcode(4)_第1张图片
思路简单直接根据规律遍历就行了;

 public String convert(String s, int numRows) {
        
        StringBuilder[] str = new StringBuilder[numRows];
        for(int i = 0 ; i < str.length ; i++)
        {
            str[i] = new StringBuilder();
        }
        int i = 0;
        char[] c = s.toCharArray();
        int len = c.length;
        while(i < len)
        {
            for(int index = 0 ; index < numRows && i < len; index ++)//直接向下遍历
            {
                str[index].append(c[i]);
                i++;
            }
            for(int index =  numRows - 2; index >= 1 && i < len; index--)//向上遍历
            {
                str[index].append(c[i]);
                i++;
            }
        }
            for(int index = 1 ; index < str.length; index++)//连起来
            {
                str[0].append(str[index]);
            }
        return str[0].toString();
        
    }

你可能感兴趣的:(leetcode)