leetcode-6-ZigZag Conversion

Posted pathjh

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode-6-ZigZag Conversion相关的知识,希望对你有一定的参考价值。

题目: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 s, int numRows);

Example 1:

Input: s = "PAYPALISHIRING", numRows = 3
Output: "PAHNAPLSIIGYIR"

Example 2:

Input: s = "PAYPALISHIRING", numRows = 4
Output: "PINALSIGYAHRPI"
Explanation:

P     I    N
A   L S  I G
Y A   H R
P     I

思路:我觉得这就是一个找规律的题,写出一个字符串后,从第一行开始找,寻找每一行字母之间的关系
举例:
对于字符串s,设总行数为n=5
行数 起始字母下标 本行下一个字母的位置偏移数
one 0 (5-one)*2
               上:0
two 1 下:(5-two)*2
               上:(two-1)*2
three 2 下:(5-three)*2
               上:(three-1)*2
four 3 下:(5-four)*2
上:(four-1)*2
five 4 下:(5-five)*2=0
             上:(5-1)*2=8

代码如下:

 1 class Solution {
 2     public  String convert(String s, int n) {
 3         if(s.length()<=n||n == 1) return s;
 4                 StringBuilder sb=new StringBuilder();
 5                 for(int row=1;row<=n;row++){
 6                     int firstChar=row-1;
 7                     int down=(n-row)*2;
 8                     int up=(row-1)*2;
 9                     sb.append(s.charAt(firstChar));
10                     while(firstChar<s.length()){
11                         if(down+firstChar>=s.length())break;
12                         else if(down!=0){
13                             sb.append(s.charAt(firstChar+down));
14                             firstChar=firstChar+down;
15                         }
16                         if(up+firstChar>=s.length()) break;
17                         else if(up!=0) {
18                             sb.append(s.charAt(firstChar+up));
19                             firstChar=firstChar+up;
20                         }
21                     }
22                 }
23                 return sb.toString();
24     }
25 }

You are here! 
Your runtime beats 99.22 % of java submissions.哈哈,感觉该没这么快吧。。。



以上是关于leetcode-6-ZigZag Conversion的主要内容,如果未能解决你的问题,请参考以下文章

6. 锯齿形变换 [leetcode 6: ZigZag Conversion]

6. 锯齿形变换 [leetcode 6: ZigZag Conversion]

学习(Swift)Leetcode 6. ZigZag Conversion

[LeetCode]6.ZigZag Conversion

[LeetCode] 6. ZigZag Conversion ☆☆☆

LeetCode 6. ZigZag Conversion