06. Z字型变换

题目:

提交01:

 1 class Solution {
 2     
 3     public String convert(String s, int numRows) {
 4         int length = 2*numRows-2;
 5          if(numRows==1||s.equals("")||s.length()<=numRows){
 6             return s;
 7         }
 8         int loop = s.length()/length;
 9         StringBuilder str = new StringBuilder();
10 
11         for(int i=0;i<numRows;i++){
12             str.append(s.charAt(i));
13             if(i!=0&&i!=numRows-1&&length-i<s.length()) {
14                 str.append(s.charAt(length - i));
15             }
16 
17 
18             for(int k=1;k<loop+1;k++){
19                 if(length*k+i<s.length()){
20                     str.append(s.charAt(length*k+i));
21                 }
22 
23                 if(i!=0&&i!=numRows-1&&length*(k+1)-i<s.length()){
24                     str.append(s.charAt(length*(k+1)-i));
25                 }
26 
27             }
28         }
29         return str.toString();
30     }
31     
32 }

 代码有点乱,很多地方需要改进

提交02

 1 class Solution {
 2     
 3     public String convert(String s, int n) {
 4          if(n==1||s.equals("")||s.length()<=n){
 5             return s;
 6         }
 7         char[] ch =s.toCharArray();
 8         int length = 2*n-2;
 9         StringBuilder str = new StringBuilder();
10         for(int i=0;i<n;i++){
11             for(int k=0;k<=ch.length/length;k++){
12                 int index = length*k+i;
13                 if(index<ch.length){
14                     str.append(ch[index]);
15                 }
16                  index = length*(k+1)-i;
17                 if(i!=0&&i!=n-1&&index<s.length()){
18                     str.append(ch[index]);
19                 }
20             }
21         }
22         return str.toString();
23     }
24     
25 }

并没有啥实质性的提升。题目就是找规律的问题,或许换个思路

原文地址:https://www.cnblogs.com/bytecodebuffer/p/11426145.html