zoukankan      html  css  js  c++  java
  • LeetCode 06 ZigZag Conversion

    https://leetcode.com/problems/zigzag-conversion/


    水题纯考细心

    题目:依照Z字形来把一个字符串写成矩阵,然后逐行输出矩阵。

    O(n)能够处理掉

    记i为行数

    第0行和第numRow-1行。 ans += str[i+k*(numRows*2-2)], k=0,1,2,...

    其它, 每一个Z字形(事实上仅仅是一竖一斜两条线)须要加上两个,下标见代码。


    特殊处理:numRows=1的时候numRows*2-2==0 ,会死循环的。另外numRows=1的时候直接输出即可


    #include <cstdio>
    #include <cstring>
    #include <iostream>
    using namespace std;
    
    class Solution {
    public:
        string convert(string s, int numRows) {
            string ret;
            if(numRows == 1){
                return s;
            }
            for(int i=0; i<numRows; i++){
                if(i == 0 || i == numRows-1){
                    int j=i;
                    while(j<s.size()){
                        ret = ret + s[j];
                        j += numRows*2-2;
                    }
                }else{
                    int j=i;
                    while(j<s.size()){
                        ret = ret + s[j];
                        if(j+numRows*2-2-(i*2) < s.size())ret = ret + s[j+numRows*2-2-(i*2)];
                        j += numRows*2-2;
                    }
                }
    
    
            }
            return ret;
        }
    };
    
    int main(){
        string s;
        int numRows;
        Solution sol;
        while(cin >> s >> numRows){
            cout << sol.convert(s, numRows) << endl;
        }
        return 0;
    }
    







  • 相关阅读:
    ABAP接口用法
    监听textarea数值变化
    The first step in solving any problem is recognizing there is one.
    Wrinkles should merely indicate where smiles have been.
    God made relatives.Thank God we can choose our friends.
    Home is where your heart is
    ABAP跳转屏幕
    Python 工具包 werkzeug 初探
    atom通过remote ftp同步本地文件到远程主机的方法
    Mongodb学习笔记一
  • 原文地址:https://www.cnblogs.com/gavanwanggw/p/6995166.html
Copyright © 2011-2022 走看看