ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

ZigZag Conversion

2019-06-23 19:49:56  阅读:358  来源: 互联网

标签:Conversion string idx int res ZigZag nRows ++


题目描述:

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


  理解题目意思很关键。

  nRows = 3,字母排列如下:

  P          A

  A    P    L

  Y          I           (按Z字形排列)

  nRows = 4,字母排列如下:

  P               I

  A         L    S

  Y    A         H 

  P               I      (按Z字形排列)

  


  代码很简单,自己写了一个

solution1:

string convert(string s, int nRows) {
    int len = s.size();
    if(len <= 2 || nRows <=1)
        return s;
    if(len <= nRows)
        return s;
    vector<string> res(nRows);
    int num = 2 * (nRows-1);
    int *loop = new int[num];
    int i,j;
    for (i = 0;i < nRows;++i)
    {
        loop[i] = i;
    }
    for (j = nRows-2;j > 0;--j)
    {
        loop[i++] = j;
    }
    int count = len / num;
    i = 0;
    for (j = 0;j < count;++j)
    {
        for (int k = 0;k < num;++k)
        {
            res[loop[k]] += s[i++];
        }
    }
    int k = 0;
    for (;i < len;++i)
    {
        res[loop[k++]] += s[i];
    }
    for (i = 1;i < nRows;++i)
    {
        res[0] += res[i];
    }
    delete [] loop;
    return res[0];
}

  看上去太过粗糙,下面的更精简
solution2:

string convert(string s, int nRows) {
    if(nRows < 2)
        return s;
    int len = s.size();
    vector<string> res(nRows);
    int i = 0;
    while (i < len)
    {
        for (int idx = 0;idx < nRows && i < len;idx++)   // vertically down
            res[idx] += s[i++];
        for (int idx = nRows-2;idx >=1 && i < len;idx--) // obliquely up
            res[idx] += s[i++];
    }
    for (int idx = 1;idx < nRows;idx++)
        res[0] += res[idx];
    return res[0];
}

来源:https://oj.leetcode.com/discuss/10493/easy-to-understand-java-solution

  

转载于:https://www.cnblogs.com/gattaca/p/4174648.html

标签:Conversion,string,idx,int,res,ZigZag,nRows,++
来源: https://blog.csdn.net/weixin_34358365/article/details/93401731

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有