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();
        }
    }
    
     
  • 相关阅读:
    c++ 左值和右值
    C++的顶层const和底层const的理解
    TCP/IP模型中的网络层
    有关TCP/IP模型中的网络接入层
    计算机网络协议与IPv4地址
    浅析计算机网络
    海思Android开发平台如何自定义update.zip内容
    Android平台RTL蓝牙适配偶现打不开问题调试笔记
    Android的SoundPool
    Android开发之IntentService
  • 原文地址:https://www.cnblogs.com/youdiaodaxue16/p/10745572.html
Copyright © 2011-2022 走看看