leetcode 字符串转换

转载:https://www.nowcoder.com/questionTerminal/d3583975276743d3befe2ddd43156d14

问题描述:字符串PAYPALISHIRING转换为:

P   A   H   N
A P L S I I G
Y   I   R

输出为PAHNAPLSIIGYIR

解析:字符串循环周期为2*row-2(两列减去头尾的两个)

string convert(string s, int nRows) {
	if (nRows <= 1) return s;
	int t = nRows + nRows - 2; //求出循环周期
	string res = "";
	vector<string> m(nRows, res);
	for (int i = 0; i < s.length(); i++)
	{
		int a = i%t;
		if (a < nRows)  //往下走
			m[a] += s[i];
		else            //往上走
			m[t - a] += s[i];
	}
	for (int i = 0; i < nRows; i++)
		res += m[i];   //合并
       //res+=m[i]+" ";
	return res;
}
int main()
{
	string s = "PAYPALISHIRING";
	string res = convert(s, 4);
	cout << res << endl;
	system("pause");
}

猜你喜欢

转载自blog.csdn.net/liugg2016/article/details/81873036