【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 }

 

转载于:https://www.cnblogs.com/sunshineatnoon/p/3912992.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值