原文:

给定一个字符串和行数“n”。当输入字符串以之字形逐行写入时,打印由 n 行连接而成的字符串。

示例:

input: str = "abcdefgh"
       n = 2
output: "acegbdfh"
explanation: let us write input string in zig-zag fashion
             in 2 rows.
a   c   e   g   
  b   d   f   h
now concatenate the two rows and ignore spaces 
in every row. we get "acegbdfh"
input: str = "geeksforgeeks"
       n = 3
output: gsgsekfrekeoe
explanation: let us write input string in zig-zag fashion
             in 3 rows.
g       s       g       s
  e   k   f   r   e   k
    e       o       e
now concatenate the two rows and ignore spaces 
in every row. we get "gsgsekfrekeoe"

想法是遍历输入字符串。每个角色都必须到其中一行。逐个将所有字符添加到不同的行中。下面是算法:

1) create an array of n strings, arr[n]
2) initialize direction as "down" and row as 0\. the 
   direction indicates whether we need to move up or 
   down in rows. 
3) traverse the input string, do following for every
   character.
   a) append current character to string of current row.
   b) if row number is n-1, then change direction to 'up'
   c) if row number is 0, then change direction to 'down'
   d) if direction is 'down', do row  .  else do row--.
4) one by one print all strings of arr[]. 

以下是上述想法的实现。

c

// c   program to print string obtained by concatenation
// of different rows of zig-zag fashion
#include
using namespace std;
// prints concatenation of all rows of str's zig-zag fashion
void printzigzagconcat(string str, int n)
{
    // corner case (only one row)
    if (n == 1)
    {
        cout << str;     
        return;
    }  
    // find length of string
    int len = str.length();
    // create an array of strings for all n rows
    string arr[n];
    // initialize index for array of strings arr[]
    int row = 0;
    bool down; // true if we are moving down in rows,
               // else false
    // traverse through given string
    for (int i = 0; i < len;   i)
    {
        // append current character to current row
        arr[row].push_back(str[i]);
        // if last row is reached, change direction to 'up'
        if (row == n-1)
          down = false;
        // if 1st row is reached, change direction to 'down'
        else if (row == 0)
          down = true;
        // if direction is down, increment, else decrement
        (down)? (row  ): (row--);
    }
    // print concatenation of all rows
    for (int i = 0; i < n;   i)
        cout << arr[i];
}
// driver program
int main()
{
    string str = "geeksforgeeks";
    int n = 3;
    printzigzagconcat(str, n);
    return 0;
}

java 语言(一种计算机语言,尤用于创建网站)

// java program to print string
// obtained by concatenation
// of different rows of
// zig-zag fashion
import java.util.arrays;
class gfg {
    // prints concatenation
    // of all rows of str's
    // zig-zag fashion
    static void printzigzagconcat(string str,
            int n)
    {
        // corner case (only one row)
        if (n == 1)
        {
            system.out.print(str);
            return;
        }
        char[] str1 = str.tochararray();
        // find length of string
        int len = str.length();
        // create an array of
        // strings for all n rows
        string[] arr = new string[n];
        arrays.fill(arr, "");
        // initialize index for
        // array of strings arr[]
        int row = 0;
        boolean down = true; // true if we are moving
        // down in rows, else false
        // traverse through
        // given string
        for (int i = 0; i < len;   i)
        {
            // append current character
            // to current row
            arr[row]  = (str1[i]);
            // if last row is reached,
            // change direction to 'up'
            if (row == n - 1)
            {
                down = false;
            }
            // if 1st row is reached,
            // change direction to 'down'
            else if (row == 0)
            {
                down = true;
            }
            // if direction is down,
            // increment, else decrement
            if (down)
            {
                row  ;
            }
            else
            {
                row--;
            }
        }
        // print concatenation
        // of all rows
        for (int i = 0; i < n;   i)
        {
            system.out.print(arr[i]);
        }
    }
    // driver code
    public static void main(string[] args)
    {
        string str = "geeksforgeeks";
        int n = 3;
        printzigzagconcat(str, n);
    }
}
// this code is contributed by princiraj1992

python 3

# python 3 program to print
# string obtained by
# concatenation of different
# rows of zig-zag fashion
# prints concatenation of all
# rows of str's zig-zag fashion
def printzigzagconcat(str, n):
    # corner case (only one row)
    if n == 1:
        print(str)    
        return
    # find length of string
    l = len(str)
    # create an array of
    # strings for all n rows
    arr=["" for x in range(l)]
    # initialize index for
    # array of strings arr[]
    row = 0
    # traverse through
    # given string
    for i in range(l):
        # append current character
        # to current row
        arr[row]  = str[i]
        # if last row is reached,
        # change direction to 'up'
        if row == n - 1:
            down = false
        # if 1st row is reached,
        # change direction to 'down'
        elif row == 0:
            down = true
        # if direction is down,
        # increment, else decrement
        if down:
            row  = 1
        else:
            row -= 1
    # print concatenation
    # of all rows
    for i in range(n):
        print(arr[i], end = "")
# driver code
str = "geeksforgeeks"
n = 3
printzigzagconcat(str, n)
# this code is contributed
# by chitranayal

c

// c# program to print string
// obtained by concatenation
// of different rows of
// zig-zag fashion
using system;
class gfg
{
    // prints concatenation
    // of all rows of str's
    // zig-zag fashion
    static void printzigzagconcat(string str,
                                  int n)
    {
    // corner case (only one row)
    if (n == 1)
    {
        console.write(str);    
        return;
    }
    char[] str1 = str.tochararray();
    // find length of string
    int len = str.length;
    // create an array of
    // strings for all n rows
    string []arr = new string[n];
    // initialize index for
    // array of strings arr[]
    int row = 0;
    bool down = true; // true if we are moving
                      // down in rows, else false
    // traverse through
    // given string
    for (int i = 0; i < len;   i)
    {
        // append current character
        // to current row
        arr[row]  = (str1[i]);
        // if last row is reached,
        // change direction to 'up'
        if (row == n - 1)
        down = false;
        // if 1st row is reached,
        // change direction to 'down'
        else if (row == 0)
        down = true;
        // if direction is down,
        // increment, else decrement
        if(down)
        row  ;
        else
        row--;
    }
    // print concatenation
    // of all rows
    for (int i = 0; i < n;   i)
        console.write(arr[i]);
    }
    // driver code
    public static void main()
    {
        string str = "geeksforgeeks";
        int n = 3;
        printzigzagconcat(str, n);
    }
}
// this code is contributed
// by chitranayal

java 描述语言


output

gsgsekfrekeoe

时间复杂度: o(len),其中 len 为输入字符串的长度。 辅助空间: o(len) 感谢高拉夫·阿希瓦尔提出上述pg电子试玩链接的解决方案。

另一种方法: 如果假设我们逐个迭代行数 n 的虚矩阵,并打印第一行和最后一行的字符 ,对于中间行,索引将增加 i = 2(n-1) 的值,如果我们向上,索引将增加 i = 2(n-rownum-1),对于向下,索引将增加 2*rownum。下面是工作实现。在 java 中

下面是上述方法的实现:

c

// c   program for above approach
#include
using namespace std;
// function for zig-zag concatenation
string zigzagconcat(string s, int n)
{
    // check is n is less
    // or equal to 1
    if (n <= 1)
    {
        return s;
    }
    string result = "";
    // iterate rownum from 0 to n - 1
    for (int rownum = 0; rownum < n; rownum  )
    {
        int i = rownum;
        bool up = true;
        // iterate i till s.length() - 1
        while (i < s.length())
        {
            result  = s[i];
            // check is rownum is 0 or n - 1
            if (rownum == 0 || rownum == n - 1)
            {
                i  = (2 * n - 2);
            }
            else
            {
                if (up)
                {
                    i  = (2 * (n - rownum) - 2);
                }
                else
                {
                    i  = rownum * 2;
                }
                up ^= true;
            }
        }
    }
    return result;
}
// driver code
int main()
{
    string str = "geeksforgeeks";
    int n = 3;
    cout<< zigzagconcat(str, n);
}
// this code is contributed by mayank tyagi

java 语言(一种计算机语言,尤用于创建网站)

// java program for above approach
import java.lang.*;
class solution
{
    // function for zig-zag concatenation
    private static string zigzagconcat(
                                string s, int n)
    {
        // check is n is less
        // or equal to 1
        if (n <= 1)
        {
            return s;
        }
        stringbuilder result = new
                             stringbuilder();
        // iterate rownum from 0 to n - 1
        for (int rownum = 0; rownum < n; rownum  )
        {
            int i = rownum;
            boolean up = true;
            // iterate i till s.length() - 1
            while (i < s.length())
            {
                result = result.append(s.charat(i));
                // check is rownum is 0 or n - 1
                if (rownum == 0 || rownum == n - 1)
                {
                    i  = (2 * n - 2);
                }
                else
                {
                    if (up)
                    {
                        i  = (2 * (n - rownum) - 2);
                    }
                    else
                    {
                        i  = rownum * 2;
                    }
                    up ^= true;
                }
            }
        }
        return result.tostring();
    }
    // driver code
    public static void main(string[] args)
    {
        string str = "geeksforgeeks";
        int n = 3;
        system.out.println(zigzagconcat(str, n));
    }
}
// this code is contributed by sakshi sachdeva

python 3

# python program for above approach
# function for zig-zag concatenation
def zigzagconcat(s, n):
    # check is n is less 
    # or equal to 1
    if (n <= 1):
        return s
    result = ""
    # iterate rownum from 0 to n - 1
    for rownum in range(n):
        i = rownum
        up = true
        # iterate i till s.length() - 1
        while(i < len(s)):
            result  = s[i]
            # check is rownum is 0 or n - 1
            if (rownum == 0 or rownum == n - 1):
                i  = (2 * n - 2)
            else:
                if(up):
                    i  = (2 * (n - rownum) - 2)
                else:
                    i  = rownum * 2
                up ^= true
    return result
# driver code
str = "geeksforgeeks"
n = 3
print(zigzagconcat(str, n))
# this code is contributed by rag2127

c

// c# program for above approach
using system;
public class gfg{
  // function for zig-zag concatenation
  static string zigzagconcat( string s, int n)
  {
    // check is n is less 
    // or equal to 1
    if (n <= 1) 
    {
      return s;
    }
    string result="";
    // iterate rownum from 0 to n - 1
    for (int rownum = 0; rownum < n; rownum  )
    {
      int i = rownum;
      bool up = true;
      // iterate i till s.length() - 1
      while (i < s.length) 
      {
        result  = s[i];
        // check is rownum is 0 or n - 1
        if (rownum == 0 || rownum == n - 1) 
        {
          i  = (2 * n - 2);
        }
        else
        {
          if (up) 
          {
            i  = (2 * (n - rownum) - 2);
          }
          else
          {
            i  = rownum * 2;
          }
          up ^= true;
        }
      }
    }
    return result;
  }
  // driver code
  static public void main (){
    string str = "geeksforgeeks";
    int n = 3;
    console.writeline(zigzagconcat(str, n));
  }
}
// this code is contributed by avanitrachhadiya2155

java 描述语言


output

gsgsekfrekeoe

时间复杂度: o(长度)

空间复杂度: o(1)

感谢释迦牟尼提出上述pg电子试玩链接的解决方案。 如果发现任何不正确的地方,或者你想分享更多关于上面讨论的话题的信息,请写评论