zoukankan      html  css  js  c++  java
  • convert

    6. 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
    
    class Solution {
        public String convert(String s, int numRows) {
            if(numRows == 1) return s;
            List<StringBuilder> list = new ArrayList<>();
            for(int i=0; i<Math.min(numRows, s.length()); i++){
                list.add(new StringBuilder());
            }
            int currentRow = 0;
            boolean dir = false;
            for(char c: s.toCharArray()){
                list.get(currentRow).append(c);
                if(currentRow == 0 || currentRow == numRows-1) dir=!dir;
                currentRow += dir? 1 : -1;
            }
            StringBuilder stringBuilder = new StringBuilder();
            for(StringBuilder each: list){
                stringBuilder.append(each);
            }
            return stringBuilder.toString();
        }
    }
    
  • 相关阅读:
    python字符串操作
    python学习【一】基础入门
    markdown 编辑器
    jenkins学习笔记-安装
    算法
    python 修改文件内容
    python基础,python第四课
    python基础,python第三课
    python基础,python第二课
    python基础,python第一课
  • 原文地址:https://www.cnblogs.com/athony/p/13086058.html
Copyright © 2011-2022 走看看