Leetcode 6. ZigZag Conversion

来源:互联网 发布:网络购彩最新消息2016 编辑:程序博客网 时间:2024/05/16 09:36

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   NA P L S I I GY   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".

核心思想:找出循环单元 如上面的例子 当nRows是时,原串的每个字符对应的行数为 1 2 3 2 1 2 3 2 1 2 3 2 1 2 ,很容易看出循环结构为 1 2 3 2 长度为:2*3-2

代码如下:

class Solution {public:    string convert(string s, int numRows) {        if(numRows==1||s=="")            return s;        string ss[numRows];//用来存储相应行号的串        int flag;//用来存储原串字母对应行号        for(int i=0;i<s.size();i++){            flag=(i+1)%(2*numRows-2);            if(flag>numRows)                flag=2*numRows-flag;            if(flag==0)                flag=2;            ss[flag-1]+=s[i];        }        string ans;        for(int i=0;i<numRows;i++)            ans+=ss[i];        return ans;    }};




0 0
原创粉丝点击