All Downloads are FREE. Search and download functionalities are using the official Maven repository.

g0001_0100.s0006_zigzag_conversion.Solution Maven / Gradle / Ivy

There is a newer version: 1.35
Show newest version
package g0001_0100.s0006_zigzag_conversion;

// #Medium #String #2023_08_09_Time_2_ms_(99.99%)_Space_43.2_MB_(99.73%)

public class Solution {
    public String convert(String s, int numRows) {
        int sLen = s.length();
        if (numRows == 1) {
            return s;
        }
        int maxDist = numRows * 2 - 2;
        StringBuilder buf = new StringBuilder();
        for (int i = 0; i < numRows; i++) {
            int index = i;
            if (i == 0 || i == numRows - 1) {
                while (index < sLen) {
                    buf.append(s.charAt(index));
                    index += maxDist;
                }
            } else {
                while (index < sLen) {
                    buf.append(s.charAt(index));
                    index += maxDist - i * 2;
                    if (index >= sLen) {
                        break;
                    }
                    buf.append(s.charAt(index));
                    index += i * 2;
                }
            }
        }
        return buf.toString();
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy