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 class Solution {
	
	public static void main(String[] args) {
		String a = "atyrytbqweasd";
		String result = convert(a,3);
		System.out.println(result);
	}
	
    public static String convert(String s, int numRows) {
    	if(numRows == 1) return s;						//只有一行则直接返回
    	String a[] = new String[numRows];				//建立字符串类型的数组,并初始化为空
    	for(int i = 0;i<numRows;i++){
    		a[i] = "";
    	}
    	int k = 0;
    	boolean flag = false;							//用来判断数组递增或递减
    	String result = "";
    	for(int j = 0;j<s.length();j++){
    		a[k] = a[k]+s.charAt(j);
    		if(k == 0){									//在第一个数组就递增,在最后一个数组就递减
    			flag = false;
    		}
    		if(k == numRows-1){
    			flag = true;
    		}
    		if(flag == false){
    			k++;
    		}else{
    			k--;
    		}
    	}
    	for(int i = 0;i<numRows;i++){					//依次读三个数组得到结果
    		result = result+a[i];
    	}
    	return result;
    }
    
}


你可能感兴趣的:(LeetCode)