需求:将所给的字符串以“倒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. UWP自定义RadioButton实现Tab底部导航

    先看效果: 参照Android的实现方式用RadioButton来实现,但是Uwp的RadioButton并没有安卓的Selector选择器 下面是一个比较简单的实现,如果有同学有更好的实现,欢迎留言 ...

  2. linux exec操作文件描述符

    linux每一个打开文件都会关联一个文件描述符,需要的时候我们可以使用exec命令指定一个大于3的数字作为文件 linux默认文件描述符 每打开一个shell就会打开默认的三个文件描述符描0,1,2, ...

  3. nginx之 nginx虚拟机配置

    1.配置通过域名区分的虚拟机[root@mysql03 nginx]# cat conf/nginx.confworker_processes 1; events { worker_connectio ...

  4. angularjs下拉框实现渲染html

    angualrjs处于安全的考虑,插值 指令会对相应字符串进行过滤,避免出现html攻击.但是在一些时候,我们需要渲染html,比如实现一个分级的下拉框,代码如下: <body ng-app=& ...

  5. IAM

    IAM 与 权限访问控制机制 IAM , Identity and Access Management 基本概念 ARN, Amazon Resource Name : 在 AWS 里, 创建的任何资 ...

  6. swiper结合ajax的轮播图

    Swiper 是什么:是纯JavaScript打造的滑动特效插件,能够实现触屏焦点图.触屏tab切换.触屏多图切换等常用效果. 开源.免费.稳定.应用广泛. 这就是swiper简单的介绍,由于是结合a ...

  7. IT学习网站

    网站 网站定位 http://www.51cto.com/ 中国领先的IT技术网站. http://www.iteye.com/ 内容齐全,功能丰富的中文IT技术门户和社区网站. http://www ...

  8. Windows 10环境安装VIM代码补全插件YouCompleteMe

    Windows 10环境安装VIM代码补全插件YouCompleteMe 折腾一周也没搞定Windows下安装VIM代码补全插件YouCompleteMe,今天在家折腾一天总算搞定了.关键问题是在于P ...

  9. mongodb入门笔记

    mongodb作为nosql中排名第一的数据库,近年来使用的人数越来越多,作为开发人员,非常有必要了解下mongodb数据库.下面就给大家介绍下mongodb数据库的基本知识,有不对的地方欢迎指正,Q ...

  10. loadrunner 手工参数拼接与l oadrunner的url编码

    Acction() { //演示需要的一些变量,提前声明 char *name = "yezi_zh"; "; char *work = "engin" ...