题目

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)

举例:重新排列后按行顺序读取返回字符串
图片描述

实际是一个找规律的题

自己花时间的地方

大循环和小循环的顺序问题:两个循环,新字符串的索引irow和原字符串的索引is
按行展开,里面具体用is和irow去找是哪一个,最后通过is来判断该行是否结束。
所以irow是大循环。

Points

  1. 类StringBuilder 构建字符串比"a"+"b"速度更快

  2. <<左移运算符,相当于*2

  3. 字符串s变为char[] 方法char[] c = s.toCharArray();

代码一

    public String convert(String s, int r) {
        if (r == 1) return s;
        String z = "";
        char[] c = s.toCharArray();
        int N = s.length();
        for (int irow = 0; irow < r; irow++) {
            for (int is = irow,is2 = irow + (2 * (r - irow) - 2); is < N; is += 2 * r - 2) {
                z += c[is];
                if (irow != 0 && irow != r - 1) {
                    if (is2 < N) z += c[is2];
                    else break;
                    is2 += 2 * r - 2;
                }
            }
        }
        return z;
    }

代码二

    public String convert2(String s, int numRows) {
        if(numRows == 1) return s;
        int gap = (numRows-1)<<1; //*2的装逼写法
        StringBuilder result = new StringBuilder();
        for(int i=0; i<numRows; i++) {
            int current = i;
            int offset = gap - (i<<1);
            while(current<s.length()) {
                if( offset != 0 ) { 
                    // avoid inserting duplicate elements
                    // in the first and the last row
                    result.append(s.charAt(current));
                    current += offset;
                }
                offset = gap-offset;
            }
        }
        return result.toString();
    }

lindsay_bubble
26 声望11 粉丝

引用和评论

0 条评论