我是看的人家的代码
一开始我也是想要之字形给字符串赋值的 我想的的是插入 然后调试半天 代码一直错,最后想到,在前面的插入后,后面的都变了,我所设想的位置坐标不管用了…………zzz
这是错误代码
string convert(string s, int numRows) {
if(numRows<=1){
return s;
}
const int HEIGHT = numRows;
const int LEN = s.length();
int a[HEIGHT];
string str;
for(int i=0;i<HEIGHT;i++){
a[i]=i;
}
int row =0,step=1;
for(int i=0;i<LEN;i++){
str.insert(a[row],s,i,1);
a[row]++;
if(row==0){
step=1;
}else if(row==HEIGHT-1){
step=-1;
}
row+=step;
}
return str;
}
下面是正确的
string convert(string s, int nRows) {
if (nRows <= 1)
return s;
const int len = (int)s.length();
string *str = new string[nRows];
int row = 0, step = 1;
for (int i = 0; i < len; ++i)
{
str[row].push_back(s[i]);
if (row == 0)
step = 1;
else if (row == nRows - 1)
step = -1;
row += step;
}
s.clear();
for (int j = 0; j < nRows; ++j)
{
s.append(str[j]);
}
delete[] str;
return s;
}
让我比较惊讶的是string的用法,竟然还可以每个位置分别弹性扩展,真是惊了我个呆…………
以上就是这样。