方法一:

建立一个二维向量,然后用字符串去一步一步填这个向量,最后输出。效率极低(132 ms,仅战胜%2的提交记录)

#include<iostream>
#include<string>
#include<vector>
using namespace std;
string convert(string s, int numRows)
{
	int Len = s.length();
	//如果排列为1行,则原样输出
	if (numRows == 1||numRows>Len)
	{
		return s;
	}
	//单列字符
	int singleNum = numRows - 2;
	//计算所需列数
	int numColumns = (numRows-1)*ceil(Len*1.0 / (numRows + singleNum));
	//二维向量
	vector<vector<char>> values(numRows, vector<char>(numColumns));
	//表示s元素的位置
	int k = 0;
	//去填充二维向量
	for (int j = 0;j < numColumns;j++)
	{//以列为索引,开始填充数组
		for (int i = 0;i < numRows;i++)
		{
			if ((j % (numRows-1) == 0)&&k<Len)
			{
				values[i][j] = s.at(k);
				k++;
			}
			else if((j % (numRows - 1)==numRows- i-1)&&k<Len)
			{
				values[i][j] = s.at(k);
				k++;
			}
			else 
			{
				values[i][j] = '0';
			}
		}
	}
	vector<char> result(0);
	//去除0值,存入result向量
	for (int i = 0;i < numRows;i++)
	{
		for (int j = 0;j < numColumns;j++)
		{
			if (values[i][j] != '0')
			{
				result.push_back(values[i][j]);
			}
			cout << values[i][j] << "  ";//调试结果用
		}
		cout << endl;//调试结果用
	}
	//向量转string
	string answer;
	answer.resize(result.size());
	return answer.assign(result.begin(), result.end());

}

int main()
{
	string s = "PAYPALISHIRING";
	//cout << convert(s, 4);
	//cout << convert(s, 1);
	cout<< convert(s, 7);
	return 0;
}

方法二:

 

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐