码迷,mamicode.com
首页 > 编程语言 > 详细

笨方法学python(6)加分题--列表与字典的区别

时间:2014-05-07 06:00:20      阅读:365      评论:0      收藏:0      [点我收藏+]

标签:style   blog   class   code   ext   color   

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

题目要求是Z字形输出,先竖排,到了nRows之后,之后的字符放在nRows-1行,单独成一列,依次递推,到底一行后,之后的元素放在前一个元素的下方,以此类推即可。

我们的思路就是使用Vector<string>,每一个string存储一行,(以上一个字符串为例,v[0]="PAHN",v[1]="APLSIIG",v[2]="YIR"),这样存储之后依次输出即可。辅助指针i从0开始递增,知道s.size().怎么往向量中添加是从代码中可以明显看出来。

 class Solution {
public:
    string convert(string s, int nRows) {
      if(s == "" || nRows ==1)  //不用转换直接返回
        return s;
      std::vector<string> v(nRows);
      int n = s.size();
      int j = 0;
      for(int i = 0;i<n;)
      {
        while(i<n&&j<nRows)//垂直竖排的一列依次添加到向量中
        {
          v[j] = v[j]+s[i];
          j++;i++;
        }
        j = nRows-2;//从倒数第二行开始插入,因为最后一行已经添加过
        while(i<n&&j>0)//梯形的字符倒序添加到向量中
        {
          v[j] = v[j]+s[i];
          j--;i++;
        }
      }
      string str="";
      for(int k = 0;k<nRows;k++)//把向量中的添加到输出字符串中
        str = str+v[k];
      return str;
        
    }
};


笨方法学python(6)加分题--列表与字典的区别,布布扣,bubuko.com

笨方法学python(6)加分题--列表与字典的区别

标签:style   blog   class   code   ext   color   

原文地址:http://blog.csdn.net/indy889/article/details/25005175

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!