zoukankan      html  css  js  c++  java
  • 【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 }
  • 相关阅读:
    Python全栈day28(描述符应用)
    Python全栈day28(上下文管理)
    如何在B2C电子商务网站后台添加CNZZ统计代码(转)
    数据统计以及商城运营日志在电子商务中的重要性(转)
    电商企业运营规划——五年经验总结(转)
    电子商务数据运营入门——有哪些数据分析需要做 (转)
    IDC单IP绑定多域名(包括端口)
    商城自动备份
    CentOS安装crontab及使用方法(转)
    CentOS中使用Shell脚本实现每天自动备份网站文件和数据库并上传到FTP中(转)
  • 原文地址:https://www.cnblogs.com/sunshineatnoon/p/3912992.html
Copyright © 2011-2022 走看看