需求:将所给的字符串以“倒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 IO流之对象流

    对象流 1.1对象流简介 1.2对象流分类 输入流字节流处理流:ObjectInputStream,将序列化以后的字节存储到本地文件 输出流字节流处理流:ObjectOutputStream 1.3序 ...

  2. 网页中嵌入百度地图报错:The request has been blocked,the content must served over Https

    网页中嵌入百度地图 1.进入百度地图开发平台:http://lbsyun.baidu.com/index.php?title=jspopular 2.获取密钥:http://lbsyun.baidu. ...

  3. 2个问题,解决tomcat启动一闪而过和运行tomcat/bin目录下的startup.bat时报错(the CATALINA_HOME environment variable is not defined correctly)

    1.除手动使用开始菜单自启动或者程序启动TOMCAT时TOMCAT一闪而过,这时候是发生了错误,这时候我们打开BIN目录下的“startup.bat”文件,编辑,在结尾添加pause命名,这样在CMD ...

  4. js中年份、月份下拉框

    <select id="year" style="width: 100px;"></select> <select id=&quo ...

  5. 创建单页web app, 如何在chrome中隐藏工具栏 地址栏 标签栏?

    问题描述: 为使用更大的屏幕空间,在访问web应用的使用,如何隐藏地址栏.工具栏? 解决办法: 1. chrome的application mode 选项--->更多工具---->添加到桌 ...

  6. AngularJS高级程序设计读书笔记 -- 过滤器篇

    一. 过滤器基础 过滤器用于在视图中格式化展现给用户的数据. 一旦定义过滤器之后, 就可在整个模块中全面应用, 也就意味着可以用来保证跨多个控制器和视图之间的数据展示的一致性. 过滤器将数据在被指令处 ...

  7. Sql Server日期时间格式转换

    Select CONVERT(varchar(100), GETDATE(), 0): 05 16 2006 10:57AMSelect CONVERT(varchar(100), GETDATE() ...

  8. Java学习笔记--动态代理

    动态代理 1.JDK动态代理 JDK1.3之后,Java提供了动态代理的技术,允许开发者在运行期创建接口的代理实例.JDK的动态代理主要涉及到java.lang.reflect包中的两个类:Proxy ...

  9. 怀念Galois

    我的第一篇谈到具体学科的博客,还是献给我最钟爱的数学. 个人比较喜欢离散数学,并非因为曲高和寡,而是因为数学分析.概率论.拓扑学.泛函之类的高手实在太多.而离散数学更为抽象,抽象到抽象代数直接以抽象二 ...

  10. ip地址0.0.0.0与127.0.0.1的区别(转载)

    原文链接:http://blog.csdn.net/ttx_laughing/article/details/58586907 最近在项目开发中发现一个奇怪的问题,当服务器与客户端在同一台机器上时,用 ...