向string尾部添加字符:s.push_back(c);
向string中插入字符:s.insert(...)
string &insert(int p0, const char *s);——在p0位置插入字符串s
string &insert(int p0, const char *s, int n);——在p0位置插入字符串s的前n个字符
string &insert(int p0,const string &s);——在p0位置插入字符串s
string &insert(int p0,const string &s, int pos, int n);——在p0位置插入字符串s从pos开始的连续n个字符
string &insert(int p0, int n, char c);//在p0处插入n个字符c
iterator insert(iterator it, char c);//在it处插入字符c,返回插入后迭代器的位置
void insert(iterator it, const_iterator first, const_iteratorlast);//在it处插入从first开始至last-1的所有字符
void insert(iterator it, int n, char c);//在it处插入n个字符c
题目:
将字符串
"PAYPALISHIRING"
以Z字形排列成给定的行数:(下面这样的形状)
P A H N A P L S I I G Y I R
之后按逐行顺序依次排列:"PAHNAPLSIIGYIR"
思路:
由分析易知,规律满足函数公式
例如n=5
1 9 17
2 8 10 16 18
3 7 11 15 19
4 6 12 14 20
5 13 21
1 9 17 ----2*n-2
2 8 10 16 18 ----2*n-4 2
3 7 11 15 19 ----2*n-6 4
4 6 12 14 20 ----2*n-8 6
5 13 21 ----2*n-10 8
解答:
class Solution {
public:
string convert(string s, int numRows) {
string r="";
int i=0;
if(s.size()<=numRows || numRows<2)
return s;
int j=0; //行数
int pos=0; //s下标
bool d12; //加d1(d12=0) or d2(d12=1)
int d1=2*numRows-2,d2=0; //距离
while(d1>=0){
r.push_back(s[j]);
pos=j+((d1==0)?d2:d1);
d12=1;
while(pos<s.size())
{
r.push_back(s[pos]);
if(d12)
pos+=((d2==0)?d1:d2);
else
pos+=((d1==0)?d2:d1);
d12=!d12;
}
d1-=2;d2+=2;
j++;
}
return r;
}
};