码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode oj s_06

时间:2016-07-05 13:58:38      阅读:170      评论:0      收藏:0      [点我收藏+]

标签:

 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

标签:

原文地址:http://www.cnblogs.com/LinXiYohoo/p/5643107.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!