zoukankan      html  css  js  c++  java
  • OJ练习5——T6

    ZigZag Conversion

    输入一串字符,(由上到下再由下向上)Z字形循环排列后,逐行打印输出。

    例如:输入PAYPALISHIRING 输出PAHNAPLSIIGYIR

    2015.4.7重做

    【我的代码】

    string convert(string s,int nRows){
        int i, x, y, index;
        string res;
        x=2*n-2;
        for(i=0; i<n; i++)
        {
            index=i;
            res.push_back(s[index]);
            index+=x;
            y=2*n-2-x;
            while(index<s.size())
            {
                res.push_back(s[index]);
                if(y==0)
                    index+=x;
                else{
                    index+=y;
                    y=2*n-2-y;
                }
            }
            x-=2;
            if(x==0)
                x=2*n-2;
        }
        return res; }

    【评价】

    在vs上测试,n=3、4都是正确的结果。探索了每行的下标之间的规律,还是可取的。

    但是在平台上有“溢出”错误,没找到原因。

    【优美的别人的代码】

    string convert(string s, int nRows) {
        string res[nRows];
        int i = 0, j, gap = nRows-2;
        while(i < s.size()){
            for(j = 0; i < s.size() && j < nRows; ++j) res[j] += s[i++];
            for(j = gap; i < s.size() && j > 0; --j) res[j] += s[i++];
        }
        string str = "";
        for(i = 0; i < nRows; ++i)
            str += res[i];
        return str;
        }

    【评价】

    这个题目主要可以学习到字符串数组的使用

    先定义每一行一个串,按原串顺序将字符一个一个顺次放到其应该在的串中。

    其中,i是顺序遍历的,gap定义中间的“链接”部分,即有3行时,gap=1,4行时,gap=2.

    思维是正向的,代码精简。

  • 相关阅读:
    bean的注入方式
    Spring中的IOC
    BeanFactory和ApplicationContext的区别
    mysql出现锁表 com.mysql.cj.jdbc.exceptions.MySQLTransactionRollbackException: Lock wait timeout exceeded; try restarting transaction
    centos防火墙
    sql中union和union all的区别
    Sql语句中IN和exists的区别及应用
    ROLLUP,CUBE,GROUPPING详解
    通过WinRM在本机执行云服务器脚本,更新git代码
    Sqlserver2012评估期已过问题解决
  • 原文地址:https://www.cnblogs.com/ketchups-notes/p/4225576.html
Copyright © 2011-2022 走看看