• leetcode-6-Z 字形变换


    问题:

    package com.nxz.blog.otherTest;
    
    import java.util.ArrayList;
    import java.util.List;
    
    public class Test6ZigzagConversion {
    
        /**
         * z字形变换  将一个字符串按照z字形输出
         * 源字符串:    LEETCODEISHIRING
         * 输出:       LCIRETOESIIGEDHN
         * L   C   I   R
         * E T O E S I I G
         * E   D   H   N
         * <p>
         * 定义numrows个对象分别存储numrows行中的字符,定义一个移动方向,向下和向上
         * 循环将原字符串中的字符添加的numrows个对象中,
         * 最后输出
         */
        private List<StringBuffer> arr = new ArrayList<>();
    
        public String convert(String s, int numRows) {
            // 初始化三个stringbuffer对象,用来保存每一行中的字符
            for (int i = 0; i < numRows; i++) {
                arr.add(new StringBuffer());
            }
    
            // 定义一个变量,用来控制行+1  还是行-1
            boolean down = false;
            // 当前行
            int curLine = 0;
            for (char c : s.toCharArray()) {
                arr.get(curLine).append(c);
                //每当是第一行会最后一行是,控制行是增还是减(也就是控制down是true还是false)
                if (curLine == 0 || curLine == numRows - 1) {
                    down = !down;
                }
                curLine += down ? 1 : -1;
            }
    
            String res = "";
            for (int i = 0; i < arr.size(); i++) {
                res += arr.get(i).toString();
            }
            return res;
        }
    
        public static void main(String[] args) {
            Test6ZigzagConversion t = new Test6ZigzagConversion();
            String leetcodeishiring = t.convert("LEETCODEISHIRING", 3);
            System.out.println(leetcodeishiring);
    
        }
    }
  • 相关阅读:
    求一个字符串中连续出现次数最多的子串
    LintCode: Longest Common Substring
    LintCode: O(1) Check Power of 2
    LintCode: Fizz Buzz
    LintCode: 3 Sum
    LintCode: Two Sum
    LintCode: Sort Colors
    LintCode: Median of two Sorted Arrays
    LintCode: Search A 2d Matrix
    Lintcode: Sqrt(X)
  • 原文地址:https://www.cnblogs.com/nxzblogs/p/11180531.html
Copyright © 2020-2023  润新知