One classic method for composing secret messages is called a square code. the spaces are removed from the English text and the characters are written into a square (or rectangle ). the width and height of the rectangle have the constraint,
Floor (SQRT (LEN (Word) <= width, height <= Ceil (SQRT (LEN (Word )))
Among the possible squares, choose the one with the minimum area.
In case of a rectangle, the number of rows will always be smaller than the number of columns. for example, the sentence "If man was meant to stay on the ground God wowould have given us Roots" is 54 characters long, so it is written in the form of a rectangle with 7 rows and 8 columns. faster more rectangles can accomodate these characters; choose the one with minimum area such that: length * width> = Len (word)
Ifmanwas
Meanttos
Login onthe
Groundgo
Dwouldha
Vegivenu
Sroots
The coded message is obtained by reading the characters in a column, inserting a space, and then moving on to the next column towards the right. For example, the message above is coded:
Imtgdvs fearwer mayoogo anouuio ntnnlvt wttddes aohghn sseoau
You will be given a message in English with no spaces between the words. The maximum message length can be 81 characters. Print the encoded message.
Here are some more examples:
Sample input:
Haveaniceday
Sample output:
Hae and via ecy
Question: It seems that you have done similar things in leetcode.
Calculate the number of rows and columns of the encoded matrix. The number of rows = SQRT (string. Length (). The number of columns depends on whether the string length is a full number of bytes. If yes, it is the same as the number of rows. Otherwise, it is equal to the number of rows plus 1. Then, traverse the string and generate the specified string. There is no need to open a two-dimensional array space for this question, and take characters between them to form a word at the column interval.
The Code is as follows:
1 import java.util.*; 2 3 public class Solution { 4 public static void main(String[] args) { 5 Scanner in = new Scanner(System.in); 6 String string = in.next(); 7 int len = string.length(); 8 int row = (int)Math.sqrt(len); 9 int column = row*row == len?row:row+1;10 StringBuilder sb = new StringBuilder();11 12 for(int i = 0;i < column;i ++){13 for(int j = 0;i+j*column<len;j++)14 sb.append(string.charAt(i+j*column));15 sb.append(‘ ‘);16 }17 18 System.out.println(sb.toString());19 }20 }