Leetcode ZigZag Conversion
做这道题遇到几个点,记录如下
- numRows <= 1的情况需要注意
- C++ string::append不可附加字符char,顾可以考虑用push_back或+=
- java的话最好用StringBuffer,可本地修改
- 这道题的思路有些像波的传播+钟摆采样
1 class Solution { 2 public: 3 string convert(string s, int numRows) { 4 string* buffer = new string[numRows]; 5 if(numRows <= 1) 6 { 7 return s; 8 } 9 int index = 0, step = 1; 10 for(int i = 0; i < s.length(); i++) 11 { 12 if(index == 0) 13 { 14 step = 1; 15 }else if(index == numRows - 1){ 16 step = -1; 17 } 18 buffer[index] += s[i]; 19 index += step; 20 } 21 //string result; /**for saving space **/ 22 s.clear(); 23 for(int i = 0; i < numRows; i++) 24 { 25 s.append(buffer[i]); 26 } 27 delete[] buffer; 28 return s; 29 } 30 };
附上说明
void push_back ( char c ); |
Append character to string
Appends a single character to the string content, increasing its size by one.
To append more than one character at a time, refer to either member append or operator+=.