LeetCode 6. ZigZag Conversion

来源:互联网 发布:无人机网站源码 编辑:程序博客网 时间:2024/05/22 15:50



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”.



题目就是一个字符串是以ZigZag的形式读的,让你转换为正常的。通过模拟的方法就可以求解。

class Solution {public:    string convert(string s, int numRows) {        int len = s.size();        string ans="";        if(numRows==1) ans=s;        else{        for(int i =0 ;i<numRows;i++){            if(i==0){                for(int j=0;j*2*(numRows-1)<len;j++){                    ans += s[j*2*(numRows-1)];                }            }else if(i==numRows-1){                for(int j=0;j*2*(numRows-1)+numRows-1<len;j++){                    ans += s[j*2*(numRows-1)+numRows-1];                }            }else{                int j=0;                int temp = j*2*(numRows-1)+i;                for(;temp<len;){                    ans+=s[temp];                    j++;                    temp=j*2*(numRows-1)-i;                    if(temp<len){                        ans+=s[temp];                        temp = j*2*(numRows-1)+i;                    }else break;                }            }        }        }        return ans;    }};
原创粉丝点击