方法一:用一个容器作为标志位,扫描字符串,给每个字母上之字序列里面的行号,再扫描行号更新新序列
1 static int wing=[]() 2 { 3 std::ios::sync_with_stdio(false); 4 cin.tie(NULL); 5 return 0; 6 }(); 7 8 class Solution 9 { 10 public: 11 string convert(string s, int numRows) 12 { 13 if(numRows==1) 14 return s; 15 string res=s; 16 int len=s.length(); 17 vector<int> v(len,0); 18 int cur=1,flag=0; 19 for(int &i:v) 20 { 21 i=cur; 22 if(flag==0&&cur<numRows) 23 cur++; 24 else if(flag==1&&cur>1) 25 cur--; 26 else if(cur==numRows) 27 { 28 flag=1; 29 cur--; 30 } 31 else 32 { 33 flag=0; 34 cur++; 35 } 36 } 37 int pr=0; 38 for(int j=1;j<=numRows;j++) 39 { 40 for(int y=0;y<len;y++) 41 { 42 if(v[y]==j) 43 res[pr++]=s[y]; 44 } 45 } 46 return res; 47 } 48 };
方法二:这个方法有点强势,但是感觉通用性不太好,之字里面的序列单独处理首末两行,中间的一起处理
1 static int wing=[]() 2 { 3 std::ios::sync_with_stdio(false); 4 cin.tie(NULL); 5 return 0; 6 }(); 7 8 class Solution 9 { 10 public: 11 string convert(string s, int numRows) 12 { 13 if(numRows==1) 14 return s; 15 int len=s.length(); 16 string res(len,' '); 17 int interval=2*(numRows-1); 18 int pr=0; 19 for(int i=0;i<len;i+=interval) //print first row 20 res[pr++]=s[i]; 21 for(int row=1;row<numRows-1;row++) //print middle row 22 { 23 for(int i=row,j=0;i<len;j+=interval,i=j-i) 24 res[pr++]=s[i]; 25 } 26 for(int i=numRows-1;i<len;i+=interval) //print last row 27 res[pr++]=s[i]; 28 return res; 29 } 30 };