个人记录-LeetCode 6.ZigZag Conversion
2016-10-01 15:21
405 查看
问题:
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)
And then read line by line: “PAHNAPLSIIGYIR”
Write the code that will take a string and make this conversion given a number of rows:
convert(“PAYPALISHIRING”, 3) should return “PAHNAPLSIIGYIR”.
其实就是将字符串按锯齿的形式进行整理后,按顺序读出来。
将人写这种字符串的方式,用代码表现一下即可。
代码示例:
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”.
其实就是将字符串按锯齿的形式进行整理后,按顺序读出来。
将人写这种字符串的方式,用代码表现一下即可。
代码示例:
public class Solution { public String convert(String s, int numRows) { if(s == null) { return null; } if (numRows <= 1) { return s; } int len = s.length(); //为了速度比较快,采取空间换时间的方法 //分配数组存储结果的位图 char[][] temp = new char[numRows][len]; for (int i = 0; i < numRows; ++i) { for (int j = 0; j < len; ++j) { temp[i][j] = '\0'; } } char[] sChar = s.toCharArray(); int rowIndex = 0; int columnIndex = 0; //zigFlag为true,表示在处理锯齿的斜线部分 boolean zigFlag = false; for (int i = 0; i < len; ++i) { temp[rowIndex][columnIndex] = sChar[i]; if (!zigFlag) { //正常形式,竖着写,增加行号即可 if (rowIndex + 1 < numRows) { ++rowIndex; } else { --rowIndex; ++columnIndex; zigFlag = true; } continue; } //处理锯齿部分,就是斜着写,坐标处理一下就行 if (rowIndex - 1 >= 0 && columnIndex + 1 < len) { --rowIndex; ++columnIndex; } else { zigFlag = false; ++rowIndex; } } StringBuilder sb = new StringBuilder(""); for (int i = 0; i < numRows; ++i) { for (int j = 0; j < len; ++j) { if (temp[i][j] != '\0') { sb.append(temp[i][j]); } } } return sb.toString(); } }
相关文章推荐
- 个人记录-LeetCode 3.Longest Substring Without Repeating Characters
- 个人记录-LeetCode 5.Longest Palindromic Substring
- 个人记录-LeetCode 22. Generate Parentheses
- 个人记录-LeetCode 27. Remove Element
- 个人记录-LeetCode 26. Remove Duplicates from Sorted Array
- 个人记录-LeetCode 1.Two Sum
- 个人记录-LeetCode 31. Next Permutation
- 个人记录-LeetCode 20. Valid Parentheses
- 个人记录-LeetCode 19. Remove Nth Node From End of List
- 个人记录-LeetCode 29. Divide Two Integers
- 个人记录-LeetCode 7.Reverse Integer
- 个人记录-LeetCode 12. Integer to Roman
- 个人记录-LeetCode 11. Container With Most Water
- 个人记录-LeetCode 21. Merge Two Sorted Lists
- 个人记录-LeetCode 16. 3Sum Closest
- 个人记录-LeetCode 4.Median of Two Sorted Arrays
- 个人记录-LeetCode 10.Regular Expression Matching
- 个人记录-LeetCode 14. Longest Common Prefix
- 个人记录-LeetCode 24. Swap Nodes in Pairs
- 个人记录-LeetCode 30. Substring with Concatenation of All Words