[关闭]
@NewWorld 2016-09-25T23:16:12.000000Z 字数 1781 阅读 1703

LeetCode:ZigZag Conversion

LeetCode


题目链接:ZigZag Conversion

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".

第一版代码,通过模拟ZigZag Conversion的过程得到一个字符矩阵,然后遍历矩阵得到结果,代码比较丑,然而我也不想改了,将就看吧:

  1. public class Solution {
  2. public String convert(String s, int numRows) {
  3. if (s == null || numRows == 1) {
  4. return s;
  5. }
  6. int length = s.length();
  7. int baseRows = numRows - 1;
  8. // 计算结果矩阵的列数
  9. int numColumns = (length / (numRows + numRows-2)) * baseRows;
  10. int remainder = length % (numRows + numRows-2);
  11. if (remainder > numRows) {
  12. numColumns += 1+remainder-numRows;
  13. } else if (0 < remainder && remainder <= numRows) {
  14. numColumns++;
  15. }
  16. char[][] temp = new char[numRows][numColumns];
  17. // 模拟 ZigZag Conversion 过程,构造字符矩阵
  18. for (int j = 0, index = 0; j < numColumns; j++) {
  19. if ((j % baseRows) == 0) {
  20. for (int i = 0; i < numRows && index < length; i++,index++) {
  21. temp[i][j] = s.charAt(index);
  22. }
  23. } else {
  24. for (int i = numRows-2; i > 0 && index < length; i--,j++,index++) {
  25. temp[i][j] = s.charAt(index);
  26. }
  27. j--;
  28. }
  29. }
  30. // 先行后列遍历矩阵,取出结果
  31. StringBuilder val = new StringBuilder();
  32. for (int i = 0; i < numRows; i++) {
  33. for (int j = 0; j < numColumns; j++) {
  34. if (temp[i][j] != 0) {
  35. val.append(temp[i][j]);
  36. }
  37. }
  38. }
  39. return val.toString();
  40. }
  41. }

第二版代码,直接计算字符出现的顺序,不构造矩阵:

  1. public class Solution {
  2. public String convert(String s, int numRows) {
  3. if (s == null || numRows == 1) {
  4. return s;
  5. }
  6. int len = s.length();
  7. StringBuilder val = new StringBuilder();
  8. // 逐行添加字符
  9. for (int i=0; i<numRows; i++) {
  10. // 这里为了区分下降和上升两种情况,设置了一个布尔变量来进行控制
  11. boolean flag = true;
  12. for (int j=i; j<len; flag=!flag) { // 下降和上升总是交替的
  13. int pos = j;
  14. if (flag) {
  15. j += (numRows-i-1)*2; // 接下来是下降,很显然要填满下面的行(画一个凹曲线)
  16. } else {
  17. j += i*2; // 接下来是上升,很显然要填满上面的行(画一个凸曲线)
  18. }
  19. if (j == pos) { // 当前值处在矩阵边界
  20. continue;
  21. }
  22. val.append(s.charAt(pos));
  23. }
  24. }
  25. return val.toString();
  26. }
  27. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注