O(n) Java Solution, easy to understand


  • 0
    T

    public class Solution {

    public String convert(String s, int numRows) {
        if(numRows <= 0 || s == null){
            return null;
        }
        if(numRows == 1){
            return s;
        }
        int length = s.length();
        
        ArrayList<StringBuilder> list = new ArrayList<StringBuilder>();
        for(int i = 0; i < numRows; i++){
            StringBuilder builder = new StringBuilder();
            list.add(builder);
        }
        
        // round: the number for returning to the first row
        int round = 2 * numRows - 2;
        for(int i = 0; i < length; i++){
            int index = i % round > numRows - 1 ? round - i % round : i % round;
            StringBuilder builder = list.get(index);
            builder.append(s.charAt(i));
        }
        
        StringBuilder result = list.get(0);
        for(int i = 1; i < list.size(); i++){
            result.append(list.get(i).toString());
        }
        return result.toString();
    }
    

    }


Log in to reply
 

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