[leetcode#6]ZigZag Conversion

来源:互联网 发布:java httpclient post 编辑:程序博客网 时间:2024/06/05 14:58

[leetcode#6]ZigZag Conversion

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”.
题目意思如图字符串用8行进行列排列,题目要求转化成行排列时的字符串输出

这里写图片描述
思路:
找出规律,在输出第0行时,第一个字符串为s[0],接着循环加上(numRows-1)*2,输出第0行第2个字符,第3个字符类推到s[j]>n
换成第1行输出,第1行第1个字符串为 s[1],
接着循环加上(numRows-1)*2-1*2, 1*2, (numRows-1)*2-1*2, 1*2两个数字交换相加类推到s[j]>n
第p行第一个字符为s[p],接着循环加上(numRows-1)*2-p*2, p*2, (numRows-1)*2-p*2, p*2两个数字交换相加类推到s[j]>n
最后一行跟第一行一样,一直循环加(numRows-1)*2
在numrows等于1, 需注意一直加1.

class Solution {public:    string convert(string s, int numRows) {        string s1 = "";        int n = s.length();        int sum = (numRows-1)*2;        if (sum == 0)            sum = 1;        int j = 0, p = 0, minus;        for (int i = 0; i < n; i++) {            s1 += s[j];            if (p == 0 || p == numRows-1) {                j += sum;            } else {                j += sum - minus;                minus = sum-minus;            }             if (j >= n) {                p++;                minus = p*2;                j = p;            }        }        return s1;    }};
0 0
原创粉丝点击