Solve the problem by group analysis

  • 0

    Use groups to solve the problem:
    After the observation can be found, can be divided into several groups, as shown
    The length of each string and the number of rows n is: length = 2 * n-2,So we can divide the entire string into several such strings for processing.

    The subscripts of the metacharacters are divided by the length of each string group to get the remainder, we find that:
    If the remainder is 0, the character is always in the first line
    If the remainder is half the length of each string, the characters are always on the last line
    If the rest of the remainder equal to n or each string length-n characters always in the nth line.

    So I use this rule to get every layer of string and save it in an array of StringBuilder type, and finally through the array to get the final string

    class Solution {
        public String convert(String s, int numRows) {
            int len = s.length();
            StringBuilder[] str = new StringBuilder[len];//String used to store the process
            StringBuilder rs = new StringBuilder();//The string to use for the return
            for(int i = 0 ; i < str.length;i++)str[i] = new StringBuilder();
            int x = numRows*2-2;//The length of each string
            for (int i = 0,j = 0; i < len;i++){
                j = i%x;
                for (int k = 1;k<x/2;k++){
                    if(j == k||j==x-k)str[k].append(s.substring(i,i+1));
            for(int i = 0 ; i < str.length;i++)rs.append(str[i]);
            return rs.toString();

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.