Accepted Java code


  • 0
    H
    public class Solution {
        public static String convert(String s, int nRows) {
            String o = "";
            if(s.length() <= nRows || nRows == 1) {return s;}
            
            for(int i = 0; i < nRows; i++){
                if(i == 0 || i == nRows - 1){
                    for(int j = i; j < s.length(); j += 2 * nRows - 2){
                        o += s.substring(j, j + 1);
                    }
                } else{
                	int diff = 2 * nRows - 2 - 2 * i;
                	for(int j = i; j < s.length(); j += 2 * nRows - 2){
                        o += s.substring(j, j + 1);
                        if(j + diff < s.length()){
                        	o += s.substring(j + diff, j + diff + 1);
                        }
                    }
                }
            }
            return o;
        }
    }

Log in to reply
 

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