The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)
P A H N A P L S I I G Y I RAnd then read line by line: "PAHNAPLSIIGYIR"
Write the code that will take a string and make this conversion given a number of rows:
string convert(string s, int numRows);Example 1:
Input: s = "PAYPALISHIRING", numRows = 3 Output: "PAHNAPLSIIGYIR"Example 2:
Input: s = "PAYPALISHIRING", numRows = 4 Output: "PINALSIGYAHRPI" Explanation: P I N A L S I G Y A H R P I总之就是,画图找规律。。。
这里边界条件别忘记判断(其实很简单,就是判断下标是否超出了s.size()即可
class Solution { public: string convert(string s, int numRows) { if(numRows==1) return s; string ans=""; int round_size=2*(numRows-1); for(int i=0;i<numRows;i++) for(int j=0;j<=s.size()/round_size;j++){ //the first number int first = j*round_size + i; if(first < s.size()) //边界条件的写法!!! ans += s[first]; int second = first + round_size - i*2; if(i!=0 && i!=numRows-1 && second < s.size()) ans += s[second]; } return ans; } };