LeetCode ZigZag Conversion 解题报告

44 篇文章 0 订阅
43 篇文章 0 订阅
对输入字符串,做蛇形变化,然后按行输出。
https://oj.leetcode.com/problems/zigzag-conversion/

例如:The string "PAYPALISHIRING"  的蛇形变化如下:

P        A           H        N
A   P   L    S     I     I   G
Y         I            R

最后要求输出的就是:"PAHNAPLSIIGYIR"
Write the code that will take a string and make this conversion given a number of rows:
convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR".

解题思路:貌似可以通过推公式的方法得出结果,我们这里还是用程序模拟的方法得出结果。
用程序的话,初始化一个column行的字符数组,然后按照规则把原始字符串的每个字符加到对应行上,一直到字符串结尾。
以字符串"PAYPALISHIRING" 为例,  ”PAY  P   ALI  S  HIR I NG“   ,新建字符数组  matrix[3]
然后,matrix[0] = matrix[0] + "P";  matrix[1] = matrix[1] + "A";  matrix[2] = matrix[2] + "Y";
                                                        matrix[1] = matrix[1] + "P";
            matrix[0] = matrix[0] + "A";  matrix[1] = matrix[1] + "L";  matrix[2] = matrix[2] + "I"; 
                                                        matrix[1] = matrix[1] + "S";
            matrix[0] = matrix[0] + "H";  matrix[1] = matrix[1] + "I";  matrix[2] = matrix[2] + "R";

                                                        matrix[1] = matrix[1] + "I";
            matrix[0] = matrix[0] + "N";  matrix[1] = matrix[1] + "G";  


最后输出column的每个字符串:PAHN APLSIIG YIR     ,就得到最后最终结果。

public class Solution {
    public String convert(String s, int nRows) {
       if(s.length()==1||nRows==1) {
	<span style="white-space:pre">	</span>return s;
	}
		
	StringBuffer[] matrix = new StringBuffer[nRows];
	int i = 0, end = nRows - 2, index = 0;
	for(i=0;i<nRows;i++) {
	<span style="white-space:pre">	</span>matrix[i] = new StringBuffer("");
	}

	while(index<s.length()) {
		//向下扩展
<span style="white-space:pre">		</span>for(i=0;index<s.length()&&i<=(nRows-1);i++) {
			matrix[i].append(s.charAt(index++));
		}	
		//斜上扩展,也就是向上	
		for(end=nRows-2;index<s.length()&&end>0;end--) {
			matrix[end].append(s.charAt(index++));
		}
	}
		
        StringBuffer result = new StringBuffer("");
	for(int a=0;a<nRows;a++) {
		result.append(matrix[a]);
	}
	//System.out.println("result="+result.toString());
	return result.toString();
    }
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值