zoukankan      html  css  js  c++  java
  • leetcode第六题 ZigZag Conversion (java)

    ZigZag Conversion

    The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)

    P   A   H   N
    A P L S I I G
    Y   I   R
    
    And then read line by line: "PAHNAPLSIIGYIR"

    Write the code that will take a string and make this conversion given a number of rows:

    string convert(string text, int nRows);
    convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR".

    思路:列输入-->行输出,将zigzag字符串看成是字符数组,为空的位置其值为null

             先确定数组的列数(nRows即为数组的行数)

    time=440ms accepted

    public class Solution {
        public String convert(String s, int nRows) {
    		    int length=s.length();
    		    if(length<=nRows||nRows==1)
    		    	return s;
    	        int updown=0,i=0,j=1,count=0,nLines=0;
    	        while(count<length){	        	
    	        	if(updown==0){				
    	        		if(i>nRows-1){
    	        			updown=nRows-1;
    	        			i=nRows-2;
    	        		}else{
    	        			count++;
    		        		i++; 
    	        		}
    	        	}
    	        	if(updown==nRows-1){		        		
    	        		if(i<1){
    	        			updown=0;
    	        			i=0;
    	        			j++;
    	        		}else{
    	        			count++;
    		        		i--;
    		        		j++;
    	        		}
    	        	}        	
    	        }
    	        nLines=j;
    	        System.out.println("j="+j);
    	        char[][] zigzag=new char[nRows][nLines];
    	        updown=0;i=0;j=0;count=0;
    	        while(count<length){	        	
    	        	if(updown==0){				
    	        		if(i>nRows-1){
    	        			updown=nRows-1;
    	        			i=nRows-2;
    	        			j++;
    	        		}else{
    	        			zigzag[i][j]=s.charAt(count);	
    	        			count++;
    		        		i++; 
    	        		}
    	        	}
    	        	if(updown==nRows-1){		        		
    	        		if(i<1){
    	        			updown=0;
    	        			i=0;	
    	        		}else{
    	        			zigzag[i][j]=s.charAt(count);
    	        			count++;
    		        		i--;
    		        		j++;
    	        		}
    	        	}        	
    	        }
    	        StringBuffer sb = new StringBuffer();  
    	        for(int m=0;m<nRows;m++)
    	        	for(int n=0;n<nLines;n++){
    	        		if(zigzag[m][n]!=''){
    	        			 sb.append(String.valueOf(zigzag[m][n]));
    	        		}
    	        	}
    	       
    	        return sb.toString();
    	    }
    }




  • 相关阅读:
    IOS中多版本,多设备类型支持注意事项
    runtime
    网络搜集各种iOS开源类库
    Foudation框架常用结构体和常用类
    iOS开发-正则表达式的使用方法
    Github上的iOS资料-个人记录
    iOS应用程序多语言本地化
    星期判断
    【设定本地通知为周一到周五提醒, 周末不提醒解决办法】
    iOS9 HTTPS解决办法
  • 原文地址:https://www.cnblogs.com/wennian/p/5036917.html
Copyright © 2011-2022 走看看