Chinaunix首页 | 论坛 | 博客
  • 博客访问: 80449
  • 博文数量: 29
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 225
  • 用 户 组: 普通用户
  • 注册时间: 2014-03-06 15:31
文章分类

全部博文(29)

文章存档

2015年(18)

2014年(11)

我的朋友

分类: Java

2015-01-19 11:26:49

题目:

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 text, int nRows);
convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR".

解决方案:首先关于ZigZag ,将题中所给出的例子写成如下形式会帮助理解什么是ZigZag:
P         A          H         N
 A    P    L    S     I     I    G
    Y           I           R
关键在于判断字符串中每一个字符属于哪一行,将题目中的例子数字化如下:
0     4      8        12
1  3  5  7  9   11  13
  2      6      10 
易看出,可以以4为周期将该字符串进行划分,观察每一行
第一行:0%4 = 4%4 = 8%4 = 12%4 = 0
第二行:1%4 = 5%4 = 9%4 = 13%4 = 1,3%4 = 7%4 = 11%4 = 3,3+1 = 4
第三行:2%4 = 6%4 = 10%4 =2
那么我们可以发现以下规律:对于第i行,i从0开始,其所包含的元素在字符串中的位置n(从0开始)满足以下规律:n%(划分周期)=i或者,n%(划分周期)+i =周期。于是,可以写出如下程序:

点击(此处)折叠或打开

  1. public class Solution {
  2.     public String convert(String s, int nRows) {
  3.         if(nRows == 1){
  4.             return s;
  5.         }
  6.         else{
  7.             char[] myarr = s.toCharArray();
  8.             int len = myarr.length;
  9.             String[] mystrarr = new String[nRows];
  10.             for(int m = 0; m < nRows; m++){
  11.                 mystrarr[m] = new String();
  12.             }
  13.             String result = new String();
  14.             int periodlen = 2*(nRows-1);
  15.             for(int i = 0; i < len; i++){
  16.                 int diff = i%periodlen;
  17.                 for(int j = 0; j < nRows; j++){
  18.                     if(diff == j || diff +j == periodlen){
  19.                         mystrarr[j] += myarr[i];
  20.                     }
  21.                 }
  22.             }
  23.             for(int n = 0; n < nRows; n++){
  24.                 result += mystrarr[n];
  25.             }
  26.             return result;
  27.         }
  28.         
  29.     }
  30. }

                                                                                                                                                                                                                                                                                                                                                                                                                                           
阅读(853) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~