leetcode oj s_06

Posted

tags:

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

 1 public class Solution {
 2 
 3     public static void main(String[] args) {
 4         String s = "PAYPALISHIRING";
 5         String res = convert(s, 4);
 6         System.out.println(res);
 7     }
 8 
 9     /**
10      * numRows=1和numRows=2为特殊情况
11      */
12     public static String convert(String s, int numRows) {
13         String res = "";
14         int l = s.length();
15         if (l == 0) {
16             return "";
17         }
18 
19         if (l > 0 && l <= numRows) {
20             return s;
21         }
22 
23         if (numRows == 1) {
24             return s;
25         }
26 
27         // col为列数
28         int col = l / (2 * numRows - 2);
29         int remainder = l % (2 * numRows - 2);
30         if (remainder >= 0 && remainder <= numRows) {
31             col = 2 * col + 1;
32         }
33         if (remainder > numRows) {
34             col = 2 * col + 2;
35         }
36 
37         // temp为辅助数组
38         int[] temp = new int[col];
39         temp[0] = 1;
40         for (int i = 1; i < col; i++) {
41             temp[i] = 2 * i * (numRows - 1) - temp[i - 1];
42         }
43         for (int i = 0; i < numRows; i++) {
44             if (i == 0) {
45                 int j = 0;
46                 while (2 * j * (numRows - 1) < l) {
47                     res += s.charAt(2 * j * (numRows - 1));
48                     j++;
49                 }
50                 continue;
51             }
52             if (i == numRows - 1) {
53                 int j = 0;
54                 while ((2 * j + 1) * (numRows - 1) < l) {
55                     res += s.charAt((2 * j + 1) * (numRows - 1));
56                     j++;
57                 }
58                 continue;
59             }
60             for (int k = 0; k < col; k++) {
61                 if (k == 0 && i < l) {
62                     res += s.charAt(i);
63                     continue;
64                 }
65                 
66                 if(k%2==0){
67                     if(temp[k]+i-1<l){
68                         res += s.charAt(temp[k]+i-1);
69                         continue;
70                     }
71                 }
72                 
73                 if (k % 2 == 1) {
74                     if (temp[k] - i + 1 < l) {
75                         res += s.charAt(temp[k] - i + 1);
76                         continue;
77                     }
78                 }
79                 break;
80             }
81 
82         }
83 
84         return res;
85     }
86 }

 思路:

技术分享

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

leetcode oj提交代码方式是怎样的?

LeetCode OJ 119. Pascal's Triangle II

项目:在线OJ--MinMIn‘s Online OJ

LeetCode OJ_题解(python):027-Remove Element ArrayEasy

LeetCode OJ_题解(python):035-Search Insert PositionArrayEasy

LeetCode OJ_题解(python):001-Two Sum ArrayEasy