zoukankan      html  css  js  c++  java
  • [Leetcode]6. Z 字形变换

    题目描述

    将一个给定字符串 s 根据给定的行数 numRows ,以从上往下、从左到右进行 Z 字形排列。

    比如输入字符串为 "PAYPALISHIRING" 行数为 3 时,排列如下:

    P   A   H   N
    A P L S I I G
    Y   I   R
    

    之后,你的输出需要从左往右逐行读取,产生出一个新的字符串,比如:"PAHNAPLSIIGYIR"。

    请你实现这个将字符串进行指定行数变换的函数:

    string convert(string s, int numRows);
    
    • 示例 1:
    输入:s = "PAYPALISHIRING", numRows = 3
    输出:"PAHNAPLSIIGYIR"
    
    • 示例 2:
    输入:s = "PAYPALISHIRING", numRows = 4
    输出:"PINALSIGYAHRPI"
    解释:
    P     I    N
    A   L S  I G
    Y A   H R
    P     I
    
    • 示例 3:
    输入:s = "A", numRows = 1
    输出:"A"
    
    • 提示:
    1 <= s.length <= 1000
    s 由英文字母(小写和大写)、',' 和 '.' 组成
    1 <= numRows <= 1000
    

    代码实现

    class Solution {
    
      public String convert(String s, int numRows) {
        if (numRows < 2) {
          return s;
        }
        StringBuilder[] rows = new StringBuilder[numRows + 1];
        for (int i = 0; i < rows.length; i++) {
          rows[i] = new StringBuilder();
        }
        //行号
        int rowIndex = 1;
        //标识是行号增加还是减小 行号从1增加到
        int flag = -1;
        for (char c : s.toCharArray()) {
          rows[rowIndex].append(c);
          if (rowIndex == 1 || rowIndex == numRows) {
            flag = -flag;
          }
          rowIndex += flag;
        }
        return String.join("", rows);
      }
    
      public static void main(String[] args) {
        System.out.println(new Solution().convert("PAYPALISHIRING", 3));
        System.out.println(new Solution().convert("AB", 1));
      }
    }
    

    以下边的为例,遍历顺序为从第一行到第三行,再从第三行到第一行,依次往复。

    P   A   H   N
    A P L S I I G
    Y   I   R
    
  • 相关阅读:
    跟风!发一篇我常用VS开发技巧
    引用:程序员最常犯的五大非技术性错误
    Introduction to the Oracle Database 3
    Oracle Database 12c 12大新特性详解
    Streams全库复制
    Introduction to the Oracle Database 2
    Oracle FlashBack
    Oracle Database Features 2
    Oracle Database Features
    TNSName配置小结
  • 原文地址:https://www.cnblogs.com/strongmore/p/14453931.html
Copyright © 2011-2022 走看看