标签:leetcode
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
原文地址:http://7371901.blog.51cto.com/7361901/1598400