需求:将所给的字符串以“倒N型”输出,可以指定输出的行数
函数 String convert(String s, int numRows)
例如输入“abcdefghijklnmopqrstuvwxyz”,输出成3行;得到
a e i n q u y
bdfhjlmprtvxz
c g k o s w

下面是一个5行的例子
String s = "abcdefghijklnmopqrstuvwxyzabcdefghijklnmopqrstuvwxyzabcdefghijklnmopqrstuvwxyz";

a___i___q___y___g___o___w___e___n___u
b__hj__pr__xz__fh__mp__vx__df__lm__tv
c_g_k_o_s_w_a_e_i_n_q_u_y_c_g_k_o_s_w
df__lm__tv__bd__jl__rt__zb__hj__pr__xz
e___n___u___c___k___s___a___i___q___y

便于观察,用下划线代替空格;可以看到行末是没有空格的;
观察例子:
1.从0开始计数,第0行第0列是“a”;第4行第0列是“e”;把位于斜线的字母称为斜线位
2.完整列之间间隔为3,即5-2;对于3行的例子,间隔为1=3-2;2行的例子,间隔为0=2-2;间隔为numRows-2;
3.首行和尾行没有斜线位;观察编号,得知a到i之间间隔2*numRows-2;令zigSpace=2*numRows-2
4.对于空格数量,第0行字母之间有3个空格;第1行斜线位左边有2个空格,右边0个;
第2行斜线位左边1个空格,右边1个;第3行斜线位左边0个空格,右边2个
这里斜线位字符的位置是: 2*numRows-2 + j - 2*i(其中i为行数,j为该行第几个字符)
5.最后一列后面不再添加空格,可用游标是否越界来判断

代码中convertOneLine将结果成从左到右读成一行

 /**
  * @author Rust Fisher
  * @version 1.0
  */
 public class ZigZag {
     /**
      * @param s
      * @param numRows
      * @return The string that already sort
      */
     public static String convert(String s, int numRows) {
         if (numRows  <= 1 || s.length() < numRows || s.length() < 3) {
             return s;
         }
         String strResult = "";
         int zigSpace = 2*numRows - 2;
         int zig = numRows - 2;
         for (int i = 0; i < numRows; i++) {
             for (int j = i; j < s.length(); j+=zigSpace) {
                 strResult = strResult + s.charAt(j);
                 if (i != 0 && i != numRows - 1 && (zigSpace + j - 2*i) < s.length()) {
                     for (int inner = 0; inner < zig - i; inner++) {
                         strResult += " ";
                     }
                     strResult = strResult + s.charAt(zigSpace + j - 2*i);
                     if ((2*zigSpace + j - 2*i) <= s.length()/*true*/) {//control the final word of string
                         for (int inner = 0; inner < i - 1; inner++) {
                             strResult += " ";
                         }
                     }
                 } else {
                     if (j+zigSpace < s.length()) {//control the final word of per line
                         for (int outline = 0; outline < zig; outline++) {
                             strResult += " ";
                         }
                     }
                 }
             }
             if (i < numRows - 1) {
                 strResult += "\n";
             }
         }
         return strResult;
     }
     /**
      * @param s
      * @param numRows
      * @return one line String
      */
     public static String convertOneLine(String s, int numRows) {
         if (numRows  <= 1 || s.length() < numRows || s.length() < 3) {
             return s;
         }
         String strResult = "";
         int zigSpace = 2*numRows - 2;
         for (int i = 0; i < numRows; i++) {
             for (int j = i; j < s.length(); j+=zigSpace) {
                 strResult = strResult + s.charAt(j);
                 if (i != 0 && i != numRows - 1 && (zigSpace + j - 2*i) < s.length()) {
                     strResult = strResult + s.charAt(zigSpace + j - 2*i);
                 }
             }
         }
         return strResult;
     }
     public static void main(String args[]){
         String s = "abcdefghijklnmopqrstuvwxyzabcdefghijklnmopqrstuvwxyzabcdefghijklnmopqrstuvwxyz";
         String ss = "abcdefghijklnmopqrstuvwxyz";
         System.out.println(convert(ss,3));
         System.out.println(convertOneLine(ss,3));
         System.out.println();
         System.out.println(convert(s,5));
         System.out.println(convertOneLine(s,5));
     }
 }

输出:

a e i n q u y
bdfhjlmprtvxz
c g k o s w
aeinquybdfhjlmprtvxzcgkosw

a i q y g o w e n u
b hj pr xz fh mp vx df lm tv
c g k o s w a e i n q u y c g k o s w
df lm tv bd jl rt zb hj pr xz
e n u c k s a i q y
aiqygowenubhjprxzfhmpvxdflmtvcgkoswaeinquycgkoswdflmtvbdjlrtzbhjprxzenucksaiqy

但不得不说明的是,上面这种方法太慢了。在网上查到了另一个方法,Java代码如下:

    public String convert(String s, int numRows) {
        if (s == null || numRows < 1) return null;
        if (numRows == 1) return s;
        char[] ss = s.toCharArray();
        StringBuilder[] strings = new StringBuilder[numRows];
        for (int i = 0; i < strings.length; i++) {
            strings[i] = new StringBuilder();
        }
        int zigNum = 2 * numRows - 2;
        for (int i = 0; i < s.length(); i++) {
            int mod = i % zigNum;
            if (mod >= numRows) {
                strings[2*numRows - mod - 2].append(ss[i]);
            }
            else {
                strings[mod].append(ss[i]);
            }
        }
        for (int i = 1; i < strings.length; i++) {
            strings[0].append(strings[i].toString());
        }
        return strings[0].toString();
    }

利用了StringBuilder类来构建String

ZigZag - 曲折字符串的更多相关文章

  1. Leetcode 6 ZigZag Conversion 字符串处理

    题意:将字符串排成Z字形. PAHNAPLSIIGYIR 如果是5的话,是这样排的 P     I AP   YR H L G N  SI A    I 于是,少年少女们,自己去找规律吧 提示:每个Z ...

  2. [leetcode]6. ZigZag Conversion字符串Z形排列

    The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like ...

  3. LeetCode 6. ZigZag Conversion & 字符串

    ZigZag Conversion 看了三遍题目才懂,都有点怀疑自己是不是够聪明... 就是排成这个样子啦,然后从左往右逐行读取返回. 这题看起来很简单,做起来,应该也很简单. 通过位置计算行数: P ...

  4. Java [leetcode 6] ZigZag Conversion

    问题描述: The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows ...

  5. News common vocabulary

    英语新闻常用词汇与短语 经济篇 accumulated deficit 累计赤字 active trade balance 贸易顺差 adverse trade balance 贸易逆差 aid 援助 ...

  6. LeetCode解题录-1~50

    [leetcode]1. Two Sum两数之和 Two Pointers, HashMap Easy [leetcode]2. Add Two Numbers两数相加 Math, LinkedLis ...

  7. 理解StringBuilder

    StringBuilder objects are like String objects, except that they can be modified. Internally, these o ...

  8. [LeetCode] ZigZag Converesion 之字型转换字符串

    The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like ...

  9. LeetCode之“字符串”:ZigZag Conversion

    题目链接 题目要求: The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of ...

随机推荐

  1. Ch.3 Aray and String

    3-1 scrore  Here is a string with o and x. The length is between 1 to 80. Calcuate the score. The sc ...

  2. 浅谈Fastfds+nginx结合_单机

    一.环境 centos6.8 x64  IP:192.168.134.128 所需软件包: libfastcommon-1.0.7.zip,FastDFS_v5.05.tar.gz,nginx-1.7 ...

  3. 如何用python绘制各种图形

    1.环境 系统:windows10 python版本:python3.6.1 使用的库:matplotlib,numpy 2.numpy库产生随机数几种方法 import numpy as np nu ...

  4. MySQL 5.7中 performance_schema 替代 show profile 命令

    本文出处:http://www.cnblogs.com/wy123/p/6979499.html show profile 命令用于跟踪执行过的sql语句的资源消耗信息,可以帮助查看sql语句的执行情 ...

  5. 关于Eclipse+SVN 开发配置

    入职快一个月,学的比较慢,但学的东西很多,受益匪浅.有时候真正意义上,感受到:代码使我快乐,我爱编程. 好久没有开笔,不知道说些什么,也不知道应该说什么. 但总觉得有些东西,很想说出来,不用理会他人的 ...

  6. AmpOne

    AmpOne 基于Windows平台的Apache .PHP.Mysql 开发环境 | One intergrated tools package of Apache + PHP + MySQL fo ...

  7. asp.net mvc中html helper的一大优势

    刚上手这个框架,发现其中的html helper用起来很方便,让我们这些从web form 过渡来的coder有一种使用控件的快感,嘻嘻! 言归正传,我要说的是在使用它时,系统会自动执行表单的现场恢复 ...

  8. SimpleDateFormat日期格式(浅面)

    java中使用SimpleDateFormat类的构造函数SimpleDateFormat(String str)构造格式化日期的格式, 通过format(Date date)方法将指定的日期对象格式 ...

  9. ubuntu 系统 更改屏幕亮度为最大(15级亮度)

    历经千辛万苦终于搞定屏幕亮度,现将成果分享如下. 硬件:联想K29 系统:UBUNTU 14.04 一.执行命令 sudo gedit /etc/default/grub 二.更改文本 然后找到 GR ...

  10. MongoDB--架构搭建(主从、副本集)之主从

    此章节讲述主从架构 主从架构  -- 目前已经不建议使用,推荐使用复制集 主从配置可以在配置文件中配置 从节点可以在启动之后使用命令追加主节点,db.source.insert({"host ...