6. ZigZag Conversion

Description

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)

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

Solution

找规律

class Solution {
    public String convert(String s, int numRows) {
        if (s == null || numRows < 1) {
            return null;
        }
        
        StringBuilder sb = new StringBuilder();
        int largeStep = Math.max((numRows - 1) << 1, 1);    // important
        int smallStep = largeStep;
        
        for (int i = 0; i < numRows; ++i) {
            for (int j = i; j < s.length(); j += largeStep) {
                sb.append(s.charAt(j));
                if (smallStep > 0 && smallStep < largeStep 
                        && j + smallStep < s.length()) {
                    sb.append(s.charAt(j + smallStep));
                }
            }
            smallStep -= 2;
        }
        
        return sb.toString();
    }
}

你可能感兴趣的:(6. ZigZag Conversion)