📌  相关文章
📜  通过按列插入矩阵并按行打印来编码给定的字符串

📅  最后修改于: 2022-05-13 01:57:07.599000             🧑  作者: Mango

通过按列插入矩阵并按行打印来编码给定的字符串

给定一个字符串S和一个整数R ,任务是通过首先在具有 R 行的矩阵中以列方式从上到下填充每个字符,然后逐行打印矩阵来对字符串进行编码。

例子:

方法:该方法是使用大小为R的字符串temp数组。遍历字符串S的每个字符,并将其添加到数组tempi%R索引处的字符串末尾。现在逐行遍历临时数组以获取编码的字符串。

下面是上述方法的实现。

C++14
// C++ code to implement above approach
#include 
using namespace std;
 
// Function to encode the string
string printRowWise(string S, int R)
{
    vector temp(R);
    string ans;
 
    for (int i = 0; i < S.length(); i++)
        temp[i % R].push_back(S[i]);
 
    for (int i = 0; i < R; i++) {
        for (int j = 0; j < temp[i].size();
             j++)
            ans.push_back(temp[i][j]);
    }
    return ans;
}
 
// Driver code
int main()
{
    string S = "GeeksForGeeks";
    int R = 5;
    cout << printRowWise(S, R);
    return 0;
}


Java
// Java code to implement above approach
import java.util.*;
class GFG{
 
  // Function to encode the String
  static String printRowWise(char []S, int R)
  {
    String []temp = new String[R];
    String ans="";
 
    for (int i = 0; i < S.length; i++) {
      if(temp[i % R] == null)
        temp[i % R] = "";
      temp[i % R] += (S[i]);
    }
    for (int i = 0; i < R; i++) {
      for (int j = 0; j < temp[i].length();
           j++)
        ans+=(temp[i].charAt(j));
    }
    return ans;
  }
 
  // Driver code
  public static void main(String[] args)
  {
    String S = "GeeksForGeeks";
    int R = 5;
    System.out.print(printRowWise(S.toCharArray(), R));
  }
}
 
// This code is contributed by 29AjayKumar


Python3
# python3 code to implement above approach
 
# Function to encode the string
def printRowWise(S, R):
    temp = ["" for _ in range(R)]
    ans = ""
 
    for i in range(0, len(S)):
        temp[i % R] += S[i]
 
    for i in range(0, R):
        for j in range(0, len(temp[i])):
            ans += temp[i][j]
 
    return ans
 
# Driver code
if __name__ == "__main__":
 
    S = "GeeksForGeeks"
    R = 5
    print(printRowWise(S, R))
 
# This code is contributed by rakeshsahni


C#
// C# code to implement above approach
using System;
using System.Collections.Generic;
class GFG {
 
  // Function to encode the string
  static string printRowWise(string S, int R)
  {
    string[] temp = new string[R];
    string ans = "";
 
    for (int i = 0; i < S.Length; i++)
      temp[i % R] += S[i];
 
    for (int i = 0; i < R; i++) {
      for (int j = 0; j < temp[i].Length; j++)
        ans += (temp[i][j]);
    }
    return ans;
  }
 
  // Driver code
  public static void Main()
  {
    string S = "GeeksForGeeks";
    int R = 5;
    Console.Write(printRowWise(S, R));
  }
}
 
// This code is contributed by ukasp.


Javascript



输出
GFeeokerskGse

时间复杂度: O(N) 其中 N 是字符串的长度
辅助空间: 在)