leetcode ZigZag Conversion 006

来源:互联网 发布:php网站流量统计系统 编辑:程序博客网 时间:2024/06/04 18:02


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

Subscribe to see which companies asked this question


#include <iostream>#include <vector>#include <string>using namespace std;class Solution {public:string convert(string s, int numRows) {string ans="";if(s=="" || numRows==1) return s;int len = numRows+numRows-2;int num = s.length()/len, remain=s.length()-num*len;for(int i=0; i < num; i++) {ans+=s[i*len];}if(remain>0) ans+=s[num*len];for (int j = 1; j < numRows-1; ++j){for (int i = 0; i < num; ++i){ans += s[i*len+j];ans += s[i*len+j+2*(numRows-1-j)];}if(remain > 0) {if(num*len+j < s.length())ans += s[num*len+j];if(num*len+j+2*(numRows-1-j) < s.length())ans+= s[num*len+j+2*(numRows-1-j)];}}for (int i = 0; i < num; ++i){ans+=s[i*len+numRows-1];}if(remain > 0) {if(num*len+numRows-1 < s.length())ans+= s[num*len+numRows-1];}return ans;}};





0 0
原创粉丝点击