Leecode #5 ZigZag Conversion

一、 问题描述
Leecode第六题,题目为:

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

问题理解为:

锯齿形转换
编写代码,将给定字符串根据给定的行数转换成锯齿形表示:
ZigZag:锯齿形,如下图所示:
锯齿形

二、解题思路

(1)这种俺规律排列的图形,是有迹可循的,找出其中的数学规律,就可以成功的实现算法了;
(2)分析:
1、 首行和末行元素下标计算方法,首行下标:a(0,i)= 2 * n - 2 (n为i的行数)
2、中间行分类:a(i,j)
j为奇数时: 2 * (j - 1 - i)
j为偶数时: 2 * i
三、实现代码

class Solution {
public:
    string convert(string s, int j) {
       
        
        if (j <= 1 || s.length() == 0)
           return s;
 
        string res = "";
        int len = s.length();
        for (int i = 0; i < len && i < j; ++i)
        {
			int indx = i;
			res += s[indx];
 
            for (int k = 1; indx < len; ++k)
            {
                
                if (i == 0 || i == j - 1)
                {
                    indx += 2 * j - 2;
                }
                
                else
                {
                    if (k & 0x1)  
						indx += 2 * (j - 1 - i);
                    else indx += 2 * i;
                }
 
                
                if (indx < len)
                {
                    res += s[indx];
                }	
            }
        }
        return res;
    }
};

猜你喜欢

转载自blog.csdn.net/serena_t/article/details/90025816