LeetCode: ZigZag Conversion

没考虑到nRows == 1的情况,少数次过

 1 class Solution {

 2 public:

 3     string convert(string s, int nRows) {

 4         // Start typing your C/C++ solution below

 5         // DO NOT write int main() function    

 6         string ret;

 7         vector<string> t(nRows);

 8         if (nRows == 1) return s;

 9         int div = 2 * nRows - 2;

10         for (int i = 0; i < s.size(); i++) {

11             int pos = i % div;

12             if (pos <= nRows-1) t[pos] += s[i];

13             else t[div-pos] += s[i];

14         }

15         for (int i = 0; i < nRows; i++) ret += t[i];

16         return ret;

17     }

18 };

 C#

 1 public class Solution {

 2     public string Convert(string s, int numRows) {

 3         string ans = "";

 4         string[] t = new string[numRows];

 5         if (numRows == 1) return s;

 6         int div = 2 * numRows - 2;

 7         for (int i = 0; i < s.Length; i++) {

 8             int pos = i % div;

 9             if (pos <= numRows-1) t[pos] += s[i];

10             else t[div-pos] += s[i];

11         }

12         for (int i = 0; i < numRows; i++) ans += t[i];

13         return ans;

14     }

15 }
View Code

 

你可能感兴趣的:(conversion)