LeetCode:ZigZag Conversion

题目描述

  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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值