LeetCode:ZigZag Conversion

来源:互联网 发布:java 布尔传参判断 编辑:程序博客网 时间:2024/05/22 08:00

题目描述

  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”.

题目分析:

  题目分析
  按照以上排列就可以

代码如下:

package com.java.day01;/** * Date:     2017年4月10日 上午8:36:31 * @author   maskwang  * @since    JDK 1.6 */public class Solution {    public static String convert(String s, int numRows) {        int i=0,len=s.length(),rank=0,row=0;        char [][]c=new char[numRows][len];//默认初始化为‘\0',用二维数组存储字符        if(numRows==1){            return s; //当只有一排时候        }        StringBuilder sb=new StringBuilder();        while(i<len){   //当排完所有字符时候            if(rank==0){  //当为第一排时候,一直把rank+i,row(rank变,row不变)                while(rank<numRows&&i<len){                    c[rank][row]=s.charAt(i);                    rank++;  //rank++                    i++;                }            }            rank--;//不满足条件时候rank++,要恢复正常需要把rank--            if(rank==numRows-1){//当rank到达最后一排时候,往右上斜对角线排列                rank--;                row++;               while(rank>0&&i<len){                   c[rank][row]=s.charAt(i);                   rank--;                   row++;                   i++;               }            }        }        for(int k=0;k<numRows;k++){            for(int j=0;j<len;j++){                if(c[k][j]!='\0')                    sb.append(c[k][j]);//把有字符的地方放到字符串中            }        }            return sb.toString();    }    public static void main(String[] args) {         String s="PAYPALISHIRING";         String s2=convert(s,3);         System.out.println(s2);    }}

Note:

  一定要防止数组和字符串下标越界

  while(rank<numRows&&i<len)

  这里的第二个条件不能少,因为在还没到达最外层while时候,不加这个条件有可能造成字符串下标越界。

0 0