Leetcode 6 ZigZag Conversion

来源:互联网 发布:中国数据统计局 编辑:程序博客网 时间:2024/06/07 11:17

1. 问题描述

  给定一个字符串和一个行数,表示按照zigzag的方式扫描的结果,编写算法输出按行扫描的结果。
  que


2. 方法与思路

  首先要先明白zigzag的顺序,
  
  zigzag
  
  明白了zigzag扫描后,要确定zigzag中字符和按行扫描字符的对应关系。有两点:
  1). 每行中的列元素都会有对应的间隔span =2row2,例如行为4的zigzag扫描中,[1,7,13], [2,8,14]间隔为242=6
  2). 中间行每一个span前还会有一个元素,间隔为span2rowi
  

class Solution {public:    string convert(string s, int numRows) {        int i,j;        string str="";        if(s.length() == 0) return "";        if(numRows == 1) return s;        int span = 2*numRows-2;                for(int i = 0; i <numRows; i++)        {            j = i;            while(j < s.length())            {                       str = str+s[j];                j += span;                if(i != 0 && i != numRows-1)                    if(j-2*i < s.length()) str = str + s[j - 2*i];              }  //cout<<"i:"<<i<<"str:"<<str<<endl;        }        return str;    }};
0 0
原创粉丝点击