Java 7ms solution [beats 100%]


  • 0
    A

    Just play with indexes.

    public class Solution {
        public String convert(String s, int numRows) {
            StringBuilder result = new StringBuilder();
            int n = s.length();
            
            int x = (2*numRows)-2;
            if(n<=numRows || x==0) {
                return s;
            }
            for(int i=0; i<numRows; i++) {
                int j = i;
                int a = x-(2*i);
                if(i==0 || i==numRows-1) {
                    while(j < n) {
                        result.append(s.charAt(j));
                        j += x;
                    }
                } else {
                    boolean even = true;
                    while(j < n) {
                        result.append(s.charAt(j));
                        if(even) {
                            j += a;
                        } else {
                            j += x-a;
                        } 
                        even = !even;
                    }
                }
            }
            return result.toString();
        }
    }
    

Log in to reply
 

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