标签:click you return hrp wan nap als sed class
Medium
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 R
And 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
1 class Solution { 2 public: 3 string convert(string s, int numRows) { 4 int group = numRows + numRows - 2; 5 if (group <=1)return s; 6 int i, size = s.length(); 7 string ans = ""; 8 for (int i = 0; i < size; i += group) 9 ans+=s[i]; 10 for (int j = 1; j < numRows-1; j++) { 11 for (i = 0; i < size; i += group) { 12 if(i+j<size) 13 ans+=s[i+j]; 14 if(i+group-j<size) 15 ans+=s[i + group - j]; 16 } 17 } 18 for (int i = numRows - 1; i < size; i += group) 19 ans+=s[i]; 20 return ans; 21 } 22 };
简单的模拟,坑点在于有类似 numRows=1 的情况
19.1.20 [LeetCode 6]ZigZag Conversion
标签:click you return hrp wan nap als sed class
原文地址:https://www.cnblogs.com/yalphait/p/10295029.html