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

时间:2019-08-27
本文章向大家介绍Leetcode 6. ZigZag Conversion(找规律,水题),主要包括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 };

原文地址:https://www.cnblogs.com/shanyr/p/11419397.html