leetcode Z-shaped string

topic:

The number of a given string according to the given row, to down, left to right from the Z-shaped arrangement.

Example, the input string is the number of rows "LEETCODEISHIRING" is 3, arranged as follows:

LCIR
ETOESIIG
EDHN
After that, you need the output from left to right read line by line, produce a new string, such as: "LCIRETOESIIGEDHN".

You will realize this string conversion function specified number of lines:

string convert (string s, int numRows );
Example 1:

Input: s = "LEETCODEISHIRING", numRows = 3
Output: "LCIRETOESIIGEDHN"
Example 2:

Input: s = "LEETCODEISHIRING", numRows = 4
Output: "LDREOEIIECIHNTSG"
explanation:

L D R
E O E I I
E C I H N
T S G

Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/zigzag-conversion
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.

 

solution:

class Solution {
    public String convert(String s, int numRows) {
        if (numRows<3){
            return "";
        }
        if (s.length()<4){
            return s;
        }
        StringBuffer[] sb=new StringBuffer[numRows];
        for (int i=0; i<numRows;i++){
            sb[i]=new StringBuffer();
        }
        for (int i=0;i<s.length();i++){
            int num=i%(2*numRows-2);
            if (num<numRows){
                sb[num].append(s.charAt(i));
            }
            else{
                sb[numRows-num%(numRows-1)-1].append(s.charAt(i));
            }
        }
        for(int i=1;i<numRows;i++){
            sb[0].append(sb[i]);
        }
        return sb[0].toString();
    }

    public static void main(String[] args) {
        Solution s = new Solution ();
        System.out.println(s.convert("LEETCODEISHIRING",3));

    }
}

  Time to beat 68.75%, 98% beat memory

Guess you like

Origin www.cnblogs.com/linwenbin/p/11890696.html