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 }
  • 相关阅读:
    Caliburn.Micro代码示例
    HtmlAgilityPack解析全国区号页面到XML
    MySql避免全表扫描【转】
    jdk和tomcat环境部署
    FusionCharts ajax 调用方式
    Could not find artifact com.sun:tools:jar:1.5.0
    winform开发中绑定combox到枚举
    TextBoxButton控件的开发实现
    SendMessage函数的常用消息及其应用大全
    SqlServer2008快照隔离模式的业务应用
  • 原文地址:https://www.cnblogs.com/sunshineatnoon/p/3912992.html
Copyright © 2011-2022 走看看