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

解题思路:

  1. 这道题主要还是找规律
  2. 我的第一个想法是把字符串先用二维数组按照之字形把它存储下来,再按照行依次存储
  3. 然而在实际的操作中,我发现这样行不太通(主要还是自己太菜,没有想出来)
  4. 言归正传,我们把之字形的数据分成两部分来看,第一部分是不在拐弯中的数据,第二部分是在拐弯中的数据,即图中加粗的数据
  5. 对于没有加粗的数据,按照行来看,同一行的数据之间的间隔为 2 * nrows - 2
  6. 对于加粗的数据,它不会出现在第一行和最后一行,且它的规律为 j + 2 * nrows - 2 - 2 * i,其中 i 为行号,j 为它同行前一个元素在源字符串的位置
  7. 注意这里的二维数组,只是抽象意义上的数组,实际上并没有用二维数组来存储,我们只是假定数据已经存储在二维数组中,基于此,通过 i,j 来查找它在原字符串中的位置

代码如下:

    public String convert(String s, int nRows) {
        if(nRows < 2) return s;

        int size = 2 * nRows - 2;
        String res = "";
		
	// 按行来处理
        for(int i = 0; i < nRows; i++){
		
	    // 按照固定的间隔在每一行内依次存储
            for(int j = i; j < s.length(); j += size){
                res += s.charAt(j);
		
		// 求出加粗字体在原字符串的位置,并判断它是否满足条件
                int temp = j + size - 2 * i;
                if(i != 0 && i != nRows - 1 && temp < s.length()) res +=s.charAt(temp);
            }
        }

        return res;
    }

转载于:https://my.oschina.net/happywe/blog/3074539

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值