【Leetcode】【ZigZag conversion】【Z字形变换】【C++】

  • 题目:将给定字符串以Z字形排列成给定的行数: 如"PAYPALISHIRING" ,numRows=3

P    A    H   N

A P L S  I  I G

Y    I      R    之后从左到右排列,逐行读取字符:得到"PAHNAPLSIIGYIR"并返回

  • 思路1:将Z字形字符数组存储到一个字符数组中,然后按行读取字符。
  • 思路2:直接根据规律计算。
  • 代码1:
class Solution {
public:
    string convert(string s, int numRows) {
        int len_s=s.size();
        if(numRows==1)
            return s;
        int numCols=(numRows-1)*len_s/(numRows*2-2)+numRows-1;
        
        
        char res[numRows][numCols];
        for(int i=0;i<numRows;i++)
        {
            for(int j=0;j<numCols;j++)
            {
                res[i][j]=' ';
            }
        }
            
        int cur_row=0;
        int cur_col=0;
        bool down=true;
        for(int i=0;i<len_s;i++)
        {
            if(down)
            {
                res[cur_row][cur_col]=s[i];
                if(cur_row && cur_row==(numRows-1))
                {
                    down=false;
                    cur_row--;
                    cur_col++;
                }
                else
                {
                    cur_row++;
                }
            }
            else
            {
                res[cur_row][cur_col]=s[i];
                if(cur_row==0)
                {
                    down=true;
                    cur_row++;
                }
                else
                {
                    cur_row--;
                    cur_col++;
                }
            }
        }
        numCols=cur_col+1;
        string str="";
        for(int i=0;i<numRows;i++)
        {
            for(int j=0;j<numCols;j++)
            {
                if(res[i][j]!=' ')
                    str+=(res[i][j]);
            }
        }
        return str;
    }
};
  • 代码2:
class Solution {
public:
    string convert(string s, int numRows) {
        if(numRows==1)
            return s;
        int n=numRows*2-2;
        int len_s=s.size();
        
        string res="";
        
        for(int i=0;i<numRows;i++)
        {
            int index=i;
            
            while(index<len_s)
            {
                res+=s[index];
                
                if(i!=0 && i!=(numRows-1) && index+n-2*(i%n)<len_s)
                {
                    res+=s[index+n-2*(i%n)];
                }
                
                index=index+n;
            }  
        }
        return res;
        
    }
};

猜你喜欢

转载自www.cnblogs.com/dreamer123/p/9163063.html