Very very Easy to understand Java solution O(s.length()) time and O(numRows) space


  • 0
    T
    public class Solution {
        public String convert(String s, int numRows) {
            if(s==null || s.isEmpty() || numRows <=1 || numRows>=s.length()) return s; // base case
            
            List<String> list = new ArrayList<>();
            int listIndex = 0; // which list are we going to append the next char to
            
            boolean flag = true; // indicates that we have move the listIndex forward (for true) or backward (for false)
            
            for(int i = 0;i<s.length();i++){
                if(listIndex==list.size()){
                    list.add("");
                }
                list.set(listIndex, list.get(listIndex)+s.charAt(i));
                if(flag)
                    listIndex++;
                else listIndex--;
                if(listIndex == numRows){
                    listIndex-=2; // if we have wandered off the numRows limits, we need to get back in.
                    flag = false; // and now start moving backward
                }
                else if(listIndex<0){
                    listIndex+=2; // if we have wandered off negatively on the numRows limits, we need to get back in.
                    flag = true; // and now start moving forward
                }
            }
            // Finally, append each string inside every list that we populated above
            StringBuilder sb = new StringBuilder();
            for(int i = 0;i<list.size();i++){
                sb.append(list.get(i));
            }
            return sb.toString();
        }
    }

Log in to reply
 

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