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

分析与解答:

把字符串进行"之"字反转,非常简单的题目,比如字符串“123456789abcdd”,nRows = 4,结果为:

1              7               d

2         6   8         c    e

3    5        9    b

4              a

按行输出,“17d268ce359b4a”

找到字符间隔长度的规律,O(n)时间内完成。nRows == 1 时 ,直接返回S即可。

class Solution {
public:
    string convert(string s, int nRows) {
       if (nRows == 1)
		return s;
	const int strLen = s.length();
	char resStr[strLen + 1];
	int strGap = (nRows - 1) * 2, strInterval = 0, resIndex = 0, sIndex = 0;
	for (int i = 0; i < nRows; i++) {
		strInterval = strGap - i * 2;
		sIndex = i;
		resStr[resIndex++] = s[sIndex];
		while(sIndex + strInterval < strLen)
		 {
			if (strInterval != 0){
				resStr[resIndex++] = s[sIndex + strInterval];
				sIndex += strInterval;
			}
			strInterval = strGap - strInterval;
		}
		resStr[resIndex] = '\0';
	}
	return resStr;
    }
};


你可能感兴趣的:(String)