[Leetcode]006. ZigZag Conversion

public class Solution {
   public String convert(String s, int nRows) {
        if (s == null || s.isEmpty() || s.length() <= nRows || nRows == 1) {
            return s;
        }

        int length = s.length();

        StringBuilder sb = new StringBuilder();

        int step = 2 * (nRows - 1);
        int count = 0;

        for (int i = 0; i < nRows; i++){
            int interval = step - 2 * i;

            for (int j = i; j < length; j += step){
                   sb.append(s.charAt(j));
                   count++;
                   if (interval > 0 && interval < step && j + interval < length && count <  length) {
                        sb.append(s.charAt(j + interval));
                        count++;
                }
            }
        }
        return sb.toString();
    }
}
posted @ 2016-05-15 13:44  zhou23  阅读(107)  评论(0编辑  收藏  举报