Java instructive


  • 0
    B
    public String convert(String s, int numRows) {
        
        //create list of lists
        List<List<Character>> rows = new ArrayList<List<Character>>();
        for(int i=0; i< numRows;++i) {
            rows.add(new ArrayList<Character>());
        }
        
        char []str = s.toCharArray();
        
        // for each char add to list in zigzag order
        int rowCnt = 0;
        boolean dir=true;
        for (int i=0; i<str.length; ++i){
            rows.get(rowCnt).add(str[i]);
            
            if (dir) rowCnt++;
            else rowCnt--;
            
            if (rowCnt == 0 || rowCnt == numRows-1){
                dir = !dir;
            }
    
            rowCnt %= numRows;
        }
        
        // iterate over lists one by one and append to string builder
        StringBuilder sb = new StringBuilder();
        for(int i=0; i< numRows;++i) {
            while(!rows.get(i).isEmpty())
                sb.append(rows.get(i).remove(0));
        }
        
        return sb.toString();
    }

Log in to reply
 

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