需求:将所给的字符串以“倒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. Java之枚举----小试牛刀练习

    1.定义一个电脑品牌枚举类,其中只有固定的几个电脑品牌. 1.1简单枚举类,不设置属性和方法 package 第十四章枚举; public enum Brand { Lenovo,Dell,Accer ...

  2. [python标准库]Pickle模块

    Pickle-------python对象序列化 本文主要阐述以下几点: 1.pickle模块简介 2.pickle模块提供的方法 3.注意事项 4.实例解析 1.pickle模块简介 The pic ...

  3. Python3.6_x86通过FFpmeg获取视频或音频的时长和分辨率

    前言 前段时间公司在做流媒体服务,与许多厂家合作拿了许多视频过来,现在要对这些视频文件进行整理,通过特殊的编码排列,获取他们的时长以及分辨率,这里我遇到一个大坑,请往下面看. # -*- coding ...

  4. 作为前端,我为什么选择 Angular 2?

    转自:https://sanwen8.cn/p/2226GkX.html 没有选择是痛苦的,有太多的选择却更加痛苦.而后者正是目前前端领域的真实写照.新的框架层出不穷:它难吗?它写得快吗?可维护性怎样 ...

  5. git使用3

    如何使用/学习第三方框架? 优秀的第三方框架都在 github.com 1> 搜索 2> git clone 获得完整版本 $ git clone https://github.com/A ...

  6. 『珍藏】eclipse快捷键

    提示所有快捷键的快捷键是 ctrl+shift+L 菜单是在: window-->preferences-->general-->keys 提供能容帮助是 alt+/ Ctrl+1 ...

  7. PyQt5环境搭建及cx_freeze打包exe

    Python的图形库也有好几个,Qt文档和使用面还是要广一些. 打包成可执行文件的也有好几个,PyInstaller用的比较多,但是PyInstaller目前还不支持Python3.6(开发版支持3. ...

  8. Elasticsearch文档查询

    简单数据集 到目前为止,已经了解了基本知识,现在我们尝试用更逼真的数据集,这儿已经准备好了一份虚构的JSON,关于客户银行账户信息的.每个文档的结构如下: { , , "firstname& ...

  9. Java IO学习笔记七

    System对IO的支持 System是系统的类,其中的方法都是在控制台的输入和输出,但是通过重定向也是可以对文件的输入输出 System中定义了标准输入.标准输出和错误输出流,定义如下: stati ...

  10. java web数据库(SQL 2008+IDEA 14)环境配置

    废话少说,在之前已经配置过IDEA+Tomcat的环境之后,现在需要进行数据库配置: 1.首先,SQL SERVER2008数据库的安装 (1)将下载的sqlserver 2008数据库进行解压,点击 ...