LeetCode-6 : Z 字形变换 ★★★
2019-03-29 19:52
295 查看
版权声明:wx: Symirror https://blog.csdn.net/qq_41960416/article/details/88900583
Z 字形变换
问题描述
my 解决方案
1.创建一个与字符串等长的char[ ]数组
2.按行将元素放进新数组
3.将每个顶点作为周期的起点,则周期长度为numRows * 2 - 2
4.存放第 0 行:每个周期的第 0 个元素依次放入,由于不知道最后一个周期是否有元素,用while
5.存放第 1 行到倒数第 numRows -1 行:(对于第 j 行)每个周期的第 j 个元素 和第 T - j +1 个元素放入数组,同样用while
6.存放第 numRows 行 : 每个周期的第 numRows-1 个元素一次放入,同样用while
7.输出为字符串即可
my 源代码
import java.util.Scanner; public class LeetCode006 { //用于测试的main方法 public static void main(String[] args) { Scanner sc = new Scanner(System.in); String s = sc.nextLine(); int numRows = sc.nextInt(); String str = convert(s, numRows); System.out.println(str); } //z字变形方法 public static String convert(String s, int numRows) { //判断合法性 if( numRows < 1) { return ""; } if (s.length() == 0) return ""; if( numRows == 1) { return s; } char[] carr = new char[s.length()];// 构建新数组 int index = 0;// 存放数据的索引 int T = numRows * 2 - 2;// 创建周期数据 int n ;// 遍历时记录周期数 // 第一行 n = 0 ; while (n * T < s.length() ) { carr[index++] = s.charAt(n * T); n++; } // 第二到倒数第二行 if (numRows > 2) { for (int j = 1; j < numRows - 1; j++) { n = 0; while (n * T + j < s.length()) { if(n * T + j < s.length()) { carr[index++] = s.charAt(n * T + j); } if ((n + 1) * T - j < s.length()) carr[index++] = s.charAt((n + 1) * T - j); n++; } } } // 最后一行 n = 0; while (n * T + numRows - 1 < s.length()) { carr[index++] = s.charAt(n * T + numRows - 1); n++; } String str = String.copyValueOf(carr); return str; } }
相关文章推荐
- Z 字形变换(LeetCode)
- LeetCode题解(python)-6. Z 字形变换
- LeetCode 6 Z字形变换(字符串)
- LeetCode第6题--Z 字形变换
- leetCode第6题,Z字形变换
- leetcode Z 字形变换
- 【leetcode】Zigzag Z 字形变换
- LeetCode6.python实现:Z 字形变换问题☆☆
- 【Leetcode】6.Z字形变换
- leetcode 6. Z 字形变换(Java版)
- 【LeetCode】之字形变换
- Leetcode(C++)——6. Z 字形变换
- LeetCode6. Z 字形变换
- Z字形变换 - LeetCode
- LeetCode | 6. ZigZag Conversion(之字形变换)
- 基础算法之Z字形变换(Leetcode-6)
- leetcode解题之103. Binary Tree Zigzag Level Order Traversal java版(之字形打印二叉树)
- 【leetcode】Z字变换
- LeetCode-6. ZigZag Conversion (JAVA)(之字形转换)
- leetcode习题集——6. Z 字形变换