The easy Java solution

  • 0

    The main idea of this solution is to divide the z-shaped strings into several substring. Split method is that: taking the every character in first row as the split point. So, in the following zigzag pattern string, the spliting substring is: "PAYP", "ALIS","HIRI","NG"

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

    The index of the character in first row is 0,1,....,i-1,i, until i>s.length(), and the indexs have the following relationshiop:i = (i-1) + (numRow-1)*2.

    For the 1, 2,..., (numRow-1) row, every sunstring has two characters in every row,the index is (i+row) and ((i+1) - row), where the 'row'(starting from 0) represent which row.The last substring is a special case, it maybe has less character than other substring, but we can judge whether it is legal by whether the indes is out of bound.

    For last row, every substring has only a character belong to it,that is (i+row) or ((i+1)-row), at this time, (i+row) = ((i+1) -row).

    class Solution {
        public String convert(String s, int numRows) {
            if (numRows == 1)
                return s;
            char[] chars = s.toCharArray();
            int j = (numRows - 1) * 2;
            int n = s.length();
            StringBuilder result = new StringBuilder();
            for (int row=0; row<numRows; ++row) {
                for (int i=0; i<n; i+=j) {
                    int first = i + row, second = i + j - row;
                    if (first < n)
                    if (second<n && second < i + j && second != first)
            return result.toString();

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.