LeetCode-6. 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" .


这道题也蛮简单的,第一次用的是二维数组存储以直观的形式输出即可,方便

public String convert(String s, int numRows) {
        if(numRows==1){
        	return s;
        }
		int num = s.length();
        char[] str = s.toCharArray();
        int len = (int)Math.ceil(num*0.5/(numRows-1))*(numRows-1);
		char[][] ch = new char[numRows][len];
		
		int i=0;
		int j=0;
		boolean flag = false;
		for(int k = 0; k <str.length;k++){
			if(flag == false){
				ch[i][j] = str[k];
				i++;
				if(i == numRows-1){
					flag = true;
				}
			}else{
				ch[i][j] = str[k];
				i--;
				j++;
				if(i == 0){
					flag = false;
				}
			}
		}
		String ans="";
		for(char[] c: ch){
			for(char cc:c){
				if(cc!='\0'){
					ans+=cc;
				}
			}
		}
        return ans;
 }

后来感觉不够快,占用内存也多,就研究了一下内在函数,也比较简单,是线性对应的~

public static String convert(String s, int numRows) {
        if(numRows == 1)
        	return s;
		char[] ch = s.toCharArray();
        int len = ch.length;
        String str = "";
		for(int i = 0; i < numRows; i++){
        	for(int j = i;;j += 2*numRows-2){
        		if(j<len){
        			str += ch[j];
        		}else
        			break;
        		int k = j+2*(numRows-i-1);
        		if(k>=len){
        			break;
        		}else if(k>j && i!=0)
        			str += ch[k];
        	}
        }
		return str;
    }

不过时间不是很快,在网上搜也没看到更好的解法,就酱紫吧









你可能感兴趣的:(LeetCode-6. ZigZag Conversion)