题目地址
https://leetcode.com/problems/zigzag-conversion/
一道打印题目
我采用了 map来模拟,字符放的情况,当然这不是最好的做法,不过缺可以ac这道题。
利用map的自动排序,可以得到某个字符具体在哪个位置
ac代码如下
class Solution {
public:
string convert(string s, int numRows) {
int len = s.size();
if (numRows == 1) // 只有一行的情况
return s;
map<int, char> mp;
int j = 0;
int i = 0;
int no = 0;
while (no < len)
{
char c = s[no++];
int realno = i * len + j;
//cout << realno << " ";
mp[realno] = c;
if (j % (numRows - 1) == 0){
if (i != (numRows - 1)){ //从上往下
i++;
}
else{ // 最后一行 需要斜向上
i--;
j++;
}
}
else{ // z 斜向上
i--;
j++;
}
} // end while
string ans;
map<int, char>::iterator it = mp.begin();
while (it != mp.end())
{
ans += it->second;
++it;
}
return ans;
}
};
此题数是有规律可循的,参考
http://blog.csdn.net/pistolove/article/details/41408021
另外一种求解的ac代码如下,根据每一排数字的变化规律
class Solution {
public:
string convert(string s, int numRows) {
int len = s.size();
if (numRows == 1 || len <= 1) // 只有一行的情况
return s;
int addNum = 2 * (numRows - 1);
string ans;
for (int i = 0; i < numRows; i++)
{
int start = i;
if (start >= len)
break;
//cout << start << endl;
ans += s[start];
if (i == 0 || i == numRows - 1)
{
while (start < len){
start += addNum;
if (start >= len)
break;
//cout << start << endl;
ans += s[start];
}
}
else{
int addNumTmp1 = addNum - i * 2;
int addNumTmp2 = addNum - addNumTmp1;
bool flag = true;
while (start < len){
if (flag)
start += addNumTmp1;
else
start += addNumTmp2;
flag = !flag;
if (start >= len)
break;
//cout << start << endl;
ans += s[start];
}
}
}
return ans;
}
};