【HackerRank】Encryption

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 would have given us roots" is 54 characters long, so it is written in the form of a rectangle with 7 rows and 8 columns. Many more rectangles can accomodate these characters; choose the one with minimum area such that: length * width >= len(word)

                ifmanwas 
                meanttos         
                tayonthe 
                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 as:

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


 

题解:好像也在leetcode做过类似的题。

首先计算出编码后矩阵的行数和列数。行数=sqrt(string.length()),列数则要看字符串长度是不是完全平方数,如果是,就和行数相同,否则等于行数加1。然后遍历字符串,生成规定的串就可以了。这道题也没有必要多开一个二维数组空间,之间按照column的间隔取字符组成单词即可。

代码如下:

复制代码
 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 }
复制代码

 

posted @   SunshineAtNoon  阅读(421)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示