【LeetCode】ZigZag Conversion

来源:互联网 发布:厦门雅迅网络很烂吗 编辑:程序博客网 时间:2024/05/16 04:44

【题目】

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   NA P L S I I GY   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是什么意思,简单解释一下,就是把字符串原顺序012345……按下图所示排列:


比较直观的解法是,用一个字符串数组 string[rows] 来存储每一行,最后一拼接就是最终结果。

用一个delta表示正向还是反向,即上图中从第一行到最后一行还是最后一行到第一行。

代码如下所示:

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. public class Solution {  
  2.     public String convert(String s, int nRows) {  
  3.         int len = s.length();  
  4.         if (len == 0 || nRows <= 1return s;  
  5.           
  6.         String[] ans = new String[nRows];  
  7.         Arrays.fill(ans, "");  
  8.         int row = 0, delta = 1;  
  9.         for (int i = 0; i < len; i++) {  
  10.             ans[row] += s.charAt(i);  
  11.             row += delta;  
  12.             if (row >= nRows) {  
  13.                 row = nRows-2;  
  14.                 delta = -1;  
  15.             }  
  16.             if (row < 0) {  
  17.                 row = 1;  
  18.                 delta = 1;  
  19.             }  
  20.         }  
  21.           
  22.         String ret = "";  
  23.         for (int i = 0; i < nRows; i++) {  
  24.             ret += ans[i];  
  25.         }  
  26.         return ret;  
  27.     }  
  28. }  
0 0
原创粉丝点击