Leetcode 6. ZigZag Conversion(找规律,水题)

6. ZigZag Conversion
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 len = s.length();
 5         string ans;
 6         if(numRows==1) return s;
 7         for(int i = 0;i < numRows; i++){
 8             int left = (numRows-1-i)*2;
 9             int right = (i)*2;
10             int cnt = i;
11             int flag = 1;
12             while(cnt < len){
13                 flag = (flag+1)%2;
14                 if((left==0 && flag==0)||(right==0&&flag==1)) continue;
15                 ans+=s[cnt];
16                 if(flag==0) cnt = cnt+left;
17                 else cnt = cnt+right;
18             }
19         }
20         return ans;
21     }
22 };

 

posted on 2019-08-27 17:00  若流芳千古  阅读(141)  评论(0编辑  收藏  举报

导航