首页 > 其他 > 详细

ZigZag Conversion - LeetCode

时间:2015-10-26 07:00:47      阅读:187      评论:0      收藏:0      [点我收藏+]

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

思路:直接模拟就行。一开始想了各种下标的复杂转换,真是没有必要。

这题还学到了两个知识点:

1. 想申请一个数组的话,比如string eg[56];这样写的话所申请的数组规模必须预先给定,对于不能确定的数组,申请要动态申请,比如 string *eg = new string[num];

2. string的append和+运算的区别:append是直接在原字符串的末尾添加,+运算是生成一个新的string来存储运算结果。

 1 class Solution {
 2 public:
 3     string convert(string s, int numRows) {
 4         if (numRows == 1) return s;
 5         string *res = new string[numRows];
 6         int step = 1, row = 0;
 7         for (char c : s)
 8         {
 9             if (row == 0)
10                 step = 1;
11             else if (row == numRows - 1)
12                 step = -1;
13             res[row] += c;
14             row += step;
15         }
16         string ans;
17         for (int i = 0; i < numRows; i++)
18             ans.append(res[i]);
19         return ans;
20     }
21 };

 

ZigZag Conversion - LeetCode

原文:http://www.cnblogs.com/fenshen371/p/4910161.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!