leetcode 6. ZigZag Conversion

原创 2016年05月30日 21:12:53

The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)

P   A   H   N
A P L S I I G
Y   I   R
And then read line by line: "PAHNAPLSIIGYIR"

Write the code that will take a string and make this conversion given a number of rows:

string convert(string text, int nRows);

convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR".

 之字形转换,起初没搞清题意多测试几次后明白了,当nRows=4时,

 P     I     N      
  A   L S   I G        
   Y A   H R         
    P     I    
public class A6ZigZagConversion {

	public String convert(String s, int numRows) {
		if("".equals(s) || s == null || numRows <= 1)
			return s;
		StringBuffer[] ans = new StringBuffer[numRows];
		int i = 0, j;
		for(; i < numRows; i++) {
			ans[i] = new StringBuffer("");
		}
		i = 0;
		while(i < s.length()) {
			for(j = 0; i < s.length() && j < numRows; j++) {
				ans[j].append(s.charAt(i++));
			}
			for(j = numRows - 2; i < s.length() && j > 0; j--) {
				ans[j].append(s.charAt(i++));
			}
		}
		for(i = 1; i < numRows; i++) {
			ans[0].append(ans[i]);
		}
		return ans[0].toString();
    }
}


版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

[Java]leetcode6 ZigZag Conversion

[Java]leetcode ZigZag Conversion
  • fumier
  • fumier
  • 2015年04月12日 11:17
  • 565

[LeetCode - 字符串] 6. ZigZag Conversion

1 问题 The string “PAYPALISHIRING” is written in a zigzag pattern on a given number of rows like thi...

LeetCode 6 ZigZag Conversion

The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (y...

Leetcode 6. ZigZag Conversion The Solution of Python

The string “PAYPALISHIRING” is written in a zigzag pattern on a given number of rows like this: (you...

LeetCode 6 ZigZag Conversion(Z型转换)(String)

翻译字符串“PAYPALISHIRING”通过一个给定的行数写成如下这种Z型模式: P A H N A P L S I I G Y I R然后一行一行的读取:“PAHNAPLSII...
  • NoMasp
  • NoMasp
  • 2015年09月21日 22:22
  • 2192

[Leetcode]_6 ZigZag Conversion

Leetcode_6 ZigZag Conversion 模拟法,找规律

6. ZigZag Conversion LeetCode题解

The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (y...

LeetCode | 6. ZigZag Conversion(之字形变换)

The string “PAYPALISHIRING” is written in a zigzag pattern on a given number of rows like this: (you...

LeetCode 6 ZigZag Conversion (C,C++,Java,Python)

Problem: The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows l...

LeetCode(6)ZigZag Conversion

把一个字符串按照“之”字形复制在矩阵中,再把结果逐行逐列输出。原理和配图在这里。看上去题目很简单,实际上有些下标相关的东西我想了很久也debug了很久才弄清楚,更吐血的事情是,提交的时候说超时了。囧,...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:leetcode 6. ZigZag Conversion
举报原因:
原因补充:

(最多只允许输入30个字)