zoukankan      html  css  js  c++  java
  • Z 字形变换

    题目:

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

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

    L   C   I   R
    E T O E S I I G
    E   D   H   N
    

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

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

    string convert(string s, int numRows);

    示例 1:

    输入: s = "LEETCODEISHIRING", numRows = 3
    输出: "LCIRETOESIIGEDHN"
    

    示例 2:

    输入: s = "LEETCODEISHIRING", numRows = 4
    输出: "LDREOEIIECIHNTSG"
    解释:
    L     D     R
    E   O E   I I
    E C   I H   N
    T     S     G
    看到这个题目我们来分析一下:
      1.这个是需要一个二维数组的,因为有两个方向的变化。
      2.这两个方向分别是:(1)、先向下去放字符。(2)、然后再往右上角放字符。
     因此代码如下:
    class Solution {
        public String convert(String s, int numRows) {
            int str = s.length();
            if(numRows == 1){
                return s;
            }
            char[][] nums = new char[numRows][str];
            int row = 0;
            int col = 0;
            int index = 0;
            while(index < str){
                while(row < numRows && index < str){   //往下走
                    nums[row++][col] = s.charAt(index++);
                }
                row--;
                while(row > 0 && index < str){     //往右上角走
                    nums[--row][++col] = s.charAt(index++);
                }
                row++;
            }
            StringBuffer res = new StringBuffer();
            for(int i = 0;i < nums.length;i++){
                for(int j = 0;j < nums[i].length;j++){
                    if(nums[i][j] != ''){   //字符以""结束 
                        res.append(nums[i][j]);
                    }
                }
            }
            return res.toString();
        }
    }
    
     
  • 相关阅读:
    3、二进制的秘闻和不同进制间的转换
    Hello World!
    HDU5883 The Best Path(欧拉回路 | 通路下求XOR的最大值)
    Codeforces 722C(并查集 + 思维)
    Floyd 算法求多源最短路径
    vim 配置
    STL容器 -- Vector
    STL容器 -- Bitset
    HDU 5707 Combine String(动态规划)
    HDU 5876 Sparse Graph(补图上BFS)
  • 原文地址:https://www.cnblogs.com/youdiaodaxue16/p/10745572.html
Copyright © 2011-2022 走看看