【刷题日记-字符串操作】

     学习不易,看论文看的头昏脑涨,就来刷两题,神清气爽,也顺便做个记录,方便以后查阅    

    No 6:ZigZag Conversion

    本题就是希望能够对输入的字符串在一个假想空间排列成锯齿状的形式,并且将新的形式逐行连接成目标字符串并输出,输入为原始字符串s,和锯齿长度numRows;输出修改后的字符串。

   本题只要在纸上画画写写,就很容易找到原始下标 i 和其对应锯齿行数pos的关系。

    
class Solution {
public:
    string convert(string s, int numRows) {
       	vector<vector<char>> t;
		vector<char> tp;
		while (!tp.empty()) tp.pop_back();

		for (int i = 0; i < numRows; i++)
		{
			t.push_back(tp);
		}

		if (numRows == 1)
		{
			for (int i = 0; i < s.size(); i++)
				t[0].push_back(s[i]);
		}
		else {
			for (int i = 0; i < s.size(); i++)
			{
				int cycle = 2 * numRows - 2;
				int res = i%cycle;
				if (res < numRows)
					t[res].push_back(s[i]);
				else
					t[cycle - res].push_back(s[i]);
			}
		}
		string ans;
		for (int i = 0; i < t.size(); i++)
		{
			for (int j = 0; j < t[i].size(); j++)
			{
				ans += t[i][j];
				cout << t[i][j];
			}
			cout << endl;
		}
		return ans;
    }
};

因为c++近年用的不多,懒得查阅一些库函数,因此实现的都是利用最基本的方式,感觉后续还是要恶补一下常用函数,会省下不少功夫。。。。。。这个方法是第一个写的,但是跑出来141ms。。。打败全国2.4%的用户。。。。醉了。后来看了一下,主要体现在容器的构造以及最后字符的累加。由于c++中博主还不清楚有没有像java中stringBuffer这样的操作用于高效修改字符串,因此做了一下小的修改。

class Solution {
public:
    string convert(string s, int numRows) {
       	vector<vector<char>> t;
		vector<char> tp;
		while (!tp.empty()) tp.pop_back();

		for (int i = 0; i < numRows; i++)
		{
			t.push_back(tp);
		}

		if (numRows == 1)
		{
			for (int i = 0; i < s.size(); i++)
				t[0].push_back(s[i]);
		}
		else {
			for (int i = 0; i < s.size(); i++)
			{
				int cycle = 2 * numRows - 2;
				int res = i%cycle;
				if (res < numRows)
					t[res].push_back(s[i]);
				else
					t[cycle - res].push_back(s[i]);
			}
		}
		string ans=s;
		int p = 0;
		for (int i = 0; i < t.size(); i++)
		{
			for (int j = 0; j < t[i].size(); j++)
			{
				ans[p++]= t[i][j];
			}
		}
		return ans;
    }
};

但是跑出来46ms。。只打败24%的用户。。。然后想了一下利用空间换时间的方法,全部上数组

class Solution {
public:
    string convert(string s, int numRows) {
       	char t[1000][1000];
		int len[1000] = { 0 };
		if (numRows == 1)
		{
			for (int i = 0; i < s.size(); i++)
				t[0][len[0]++]=s[i];
		}
		else {
			for (int i = 0; i < s.size(); i++)
			{
				int cycle = 2 * numRows - 2;
				int res = i%cycle;
				if (res < numRows)
					t[res][len[res]++]=s[i];
				else
					t[cycle - res][len[cycle-res]++]=s[i];
			}
		}
		string ans = s;
		int p = 0;
		for (int i = 0; i < 1000&&len[i]!=0; i++)
		{
			for (int j = 0; j < len[i]; j++)
			{
				ans[p++] = t[i][j];
			}
		}
		return ans;
    }
};

最后终于停留在39ms,打败全国54%的用户。。。总算是超越平均水准了。。。


准备按照题目内容进行专题分类,后续将不断更新。。。

猜你喜欢

转载自blog.csdn.net/weixin_41526905/article/details/80820288