首页 > 代码库 > [LeetCode]6 ZigZag Conversion
[LeetCode]6 ZigZag Conversion
https://oj.leetcode.com/problems/zigzag-conversion/
http://fisherlei.blogspot.com/2013/01/leetcode-zigzag-conversion.html
public class Solution { public String convert(String s, int nRows) { // Solution A: return convert_NoNewMatrix(s, nRows); } ///////////////////////////// // Solution A: no new matrix // public String convert_NoNewMatrix(String s, int nRows) { if (s == null || nRows <= 0) return null; // Invalid input if (s.length() <= 1 || nRows == 1) return s; // No need to zigzag // Define a |/ as a group char[] chars = s.toCharArray(); int len = chars.length; // How many chars in each group. int groupSize = nRows * 2 - 2; // How many groups. int groupNum = ((len - 1) / groupSize ) + 1; StringBuilder sb = new StringBuilder(); // Iterate every position in the group for (int i = 0 ; i < nRows ; i ++) { for (int j = 0 ; j < groupNum ; j ++) { // calculate position of | int pos = j * groupSize + i; if (pos < len) sb.append(chars[pos]); if (i > 0 && i < nRows - 1) { pos = j * groupSize + groupSize - i; if (pos < len) sb.append(chars[pos]); } } } return sb.toString(); } ///////////////////////////// // Solution B: Create a help matrix // public String convert_NewMatrix(String s, int nRows) { // What is a zig-zag? nRows = 6 // // 0 10 // 1 9 11 // 2 8 12 // 3 7 . // 4 6 . // 5 . // We can simple use 2 columns to represents a group. if (s == null || nRows <= 0) return null; // Invalid input if (s.length() <= 1 || nRows == 1) return s; // No need to zigzag // Define a |/ as a group char[] chars = s.toCharArray(); int len = chars.length; // How many chars in each group. int groupSize = nRows * 2 - 2; // How many groups. int groupNum = ((len - 1) / groupSize ) + 1; int nCols = groupNum * 2; // Use 2 columns to represents a group. // Option 1 // Use a help matrix int k = 0; char[][] m = new char[nRows][nCols]; for (int i = 0 ; i < nCols ; i ++) { if (i % 2 == 0) { // Down for (int j = 0 ; j < nRows; j ++) { if (k < len) { m[j][i] = chars[k]; k ++; } } } else { // Up for (int j = nRows - 2 ; j > 0 ; j --) { if (k < len) { m[j][i] = chars[k]; k ++; } } } } // Finished the help matrix. // Print as required StringBuilder sb = new StringBuilder(); for (int i = 0 ; i < nRows ; i ++) { for (int j = 0 ; j < nCols ; j ++) { if (m[i][j] != 0) sb.append(m[i][j]); } } return sb.toString(); } }
[LeetCode]6 ZigZag Conversion
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。