java O(n)....


  • 0
    S
     public String convert(String s, int numRows) {
         	if(s.length()<2||s.length()<numRows||numRows==1)
    			return s;
            String[] strs=new String[numRows];
            for(int i=0;i<numRows;i++) {
            	strs[i]="";
            }
            String result="";
            int row=-1;
            boolean isVertical=true;
            char[] arr=s.toCharArray();
            for(int i=0;i<arr.length;i++) {
            	
            	if(isVertical) {
            		row++;
            	}else
            	{
            		row--;
            	}
            	strs[row]+=arr[i];
            	
            	if(row==numRows-1&&isVertical)
            	{
            		//斜着走
            		isVertical=false;
            	}else if((((numRows==2)&&(row==0))||(row==1))&&!isVertical)
            	{
            		isVertical=true;
            		if(numRows==2)
            			row=0;
            		else
            			row=-1;
            	
            	}
            }
            for(String x:strs) {
            	result+=x;
            }
            return result;
        }
    

Log in to reply
 

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