LeetCode 6 ZigZag Conversion (C,C++,Java,Python)

Problem:

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 text, int nRows);
convert("PAYPALISHIRING", 3)  should return  "PAHNAPLSIIGYIR" .

Solution:

纯粹的模拟之字形路线,时间复杂度为O(n)

题目大意:

给一个字符串,按照之字形排列成一个矩阵,然后将矩阵每一行连起来构成一个字符串,求这个字符串,题意不清,还是要给一个图才能明白
0       8       16      
1     7 9     15 17      
2   6   10   14   18      
3 5     11 13     19      
4       12       20      

解题思路:

可以将之字形路线压缩,例如上例中压缩之后的到如下表所示
0   8     16            
1 7 9   15 17            
2 6 10   14 18            
3 5 11   13 19            
4   12     20            
通过这样,然后再来模拟字符串的之字形排列,要注意一些编码细节

Java源代码(用时409ms):

public class Solution {
    public String convert(String s, int numRows) {
        if(numRows==1)return s;
        char[] chs=s.toCharArray();
        if(numRows==2){
            int index=0;
            for(int i=0;i=1 && index
C语言源代码(用时79ms):

char* convert(char* s, int numRows) {
    char* ch;
    char map[1000][1000];
    int length=0,index=0,i,j,k;
    if(numRows<=1)return s;
    for(i=0;s[i];i++)length++;
	ch = (char*)malloc(sizeof(char)*length*2);
    if(numRows==2){
        for(i=0;i=1 && s[index])map[i--][j]=s[index++];
        }else{
            i=0;
            while(i
C++源代码(用时112ms):

class Solution {
public:
    string convert(string s, int numRows) {
        if(numRows==1)return s;
        string chs=string(s);
        int index=0;
        if(numRows==2){
            for(int i=0;i=1 && s[index])map[i--][col]=s[index++];
            }else{
                int i=0;
                while(i
Python源代码(用时138ms):
class Solution:
    # @param {string} s
    # @param {integer} numRows
    # @return {string}
    def convert(self, s, numRows):
        if numRows==1:return s
        res=["" for i in range(numRows)]
        i=0;gap=numRows-2
        while i0:res[j]+=s[i];i+=1;j-=1
        chs=''
        for i in range(numRows):
            chs+=res[i]
        return chs


你可能感兴趣的:(LeetCode)