【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" .

二、问题分析

这道题本质上还是字符串的遍历问题。从给的例子中可以发现,根据rows的值我们可以初始化同样个数的子串来分别记录每行的字符内容,最后将多个子串连接一下即可。分析例子中的字符串发现,在遍历的过程中是有规律的,比如根据rows的值发现先PAY再P再ALI再S,依次类推。时间复杂度为O(n)。

三、Java AC代码

public String convert(String s, int numRows) {
        char[] str = s.toCharArray();
		String result = "";
		int len = s.length();
		String[] res = new String[numRows];
		for(int i = 0;i<numRows;i++){
			res[i] = "";
		}
		if (numRows == 1) {
			return s;
		} else {
			int i = 0, gap = numRows - 2, j;
			while (i < len) {
				for (j = 0; i < len && j < numRows; j++) {
					res[j] += str[i++];
				}
				for (j = gap; i < len && j > 0; j--) {
					res[j] += str[i++];
				}
			}
			for (i = 0; i < numRows; i++) {
				result += res[i];
			}
			return result;
		}
    }


你可能感兴趣的:(java,LeetCode,String)