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

自己的解法


= =道题刚开始的时候根本没看明白,题目的意思。= =没办法只能从网上找了一下别人的说明,才看明白了这道题目。自己对于Java的字符串处理有点不太懂(因为不像C那样可以直接用下标处理)= =所以直接看了hot解法



Hot解法

[java]
  1. public class Solution {
        public String convert(String s, int numRows) {
        int nRows = numRows; 
        char[] c = s.toCharArray();
        int len = c.length;
        StringBuffer[] sb = new StringBuffer[nRows];
        for (int i = 0; i < sb.length; i++) sb[i] = new StringBuffer();

        int i = 0;
        while (i < len) {
            for (int idx = 0; idx < nRows && i < len; idx++) // vertically down
                sb[idx].append(c[i++]);
            for (int idx = nRows-2; idx >= 1 && i < len; idx--) // obliquely up
                sb[idx].append(c[i++]);
        }
        for (int idx = 1; idx < sb.length; idx++)
            sb[0].append(sb[idx]);
        return sb[0].toString();
            
        }
    }

感受

其实看懂了这道题目,Hot解法的代码不是很难理解。通过这次的hot解法,在Java中每次我有解题的思路时,但想到不能用下标访问,我就只能去通过Java本身的一些字符串函数来处理。有些问题用本身有的函数可能没有那么好处理。这次我学会了toCharArray()这个函数,可以把字符串转换成字符数组来进行操作。最近被LeetCode虐的有点惨,不是没什么思路,就是始终无法AC。所以决定先从简单的通过率高的题目开始做起。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值