Java simple solution


  • 0
    M

    The idea is to traverse the input string. Every character has to go to one of the rows. One by one add all characters to different rows. Below is algorithm:

    '''
    public class Solution {
    public String convert(String s, int numRows) {

        String res="";
        List<String> strow = new ArrayList<>();
        for(int i=0; i<numRows; i++){
            strow.add(0, "");
        }
        int row=0;
        boolean turn=false;
        for(int i=0; i<s.length(); i++){
            char c = s.charAt(i);
            String news = strow.get(row)+String.valueOf(c);
            strow.remove(row);
            strow.add(row,news);
            if(!turn)
            	row++;
            else{
            	row--;
            }
            	
            row=row%numRows;
            
            if(row==0 && !turn){
            	row=numRows-2;
            	if(row<0)
            		row=0;
            	turn^= true;
            }
            
            if(row==0 && turn){
            	row=0;
            	turn^= true;
            }
        }
        
        for(String st: strow){
            res=res+st;
        }
        
        return res;
        
    
    }
    

    }
    ''''


Log in to reply
 

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