zoukankan      html  css  js  c++  java
  • LeetCode -- 02 Z字形变换

    题目:

      起初,看到这道题,我就是用模拟做的,不得不说还很麻烦,思路其实是比较牵强的,

    大概想法是用的二维数组,加循环,这里先展示一下我的代码

    #include<stdio.h>
    #include<algorithm>
    #include<string.h>
    #include<cmath>
    #include<iostream> 
    using namespace std;
    
    int main(){
        string a;
        int b;
        cin >>a;
        cin >> b;
        int k = 0;
        int len = a.length();
    //    cout << len;
        char map[500][500];
        int x = b-2;
        int lun = len / (b+x);
        int yu = len % (b+x);
        int m=0;
        for(int i = 0 ; i < 500 ; i ++)
        {
            for(int j = 0 ; j < 500 ; j ++)
            {
                map[i][j] = 0;
            }
        }
        while(lun --)
        {
            for(int i = 0 ; i < b ; i ++)
            {
                map[i][m] = a[k++];
            }
            int q = b-1;
            for(int p = 1 ; p <= x ; p++ )
            {
                map[--q][++m] = a[k++];
                
            }
            m++;
    //        cout << map[2][1];
        }
        
        if(yu <= b && yu != 0){
            for(int i = 0 ; i < yu ; i ++)
            {
                map[i][m] = a[k++];
            }
        }
        
        else if(yu > b){
            for(int i = 0 ; i < b; i ++)
            {
                map[i][m] = a[k++];
            }
            int q = b-1;
            for(int p = 1 ; p <= yu -b ; p ++)
            {
                map[--q][++m] = a[k++];
            }
        }
        
        
        
        
        for(int i = 0 ; i < b ; i ++)
        {
            for(int j= 0 ; j < 10 ; j ++)
            {
                 
                if(map[i][j] != 0)
                cout << map[i][j];
            }
        }
        
    } 

    运行结果:

    结果看了下大佬的写法:思路清奇

    class Solution {
    public:
    string convert(string s, int numRows) {

    if (numRows == 1) return s;

    vector<string> rows(min(numRows, int(s.size())));
    int curRow = 0;
    bool goingDown = false;

    for (char c : s) {   // for 循环的意思是遍历 s 里每一个字符
    rows[curRow] += c;
    if (curRow == 0 || curRow == numRows - 1) 
    goingDown = !goingDown;
    }
    curRow += goingDown ? 1 : -1;
    }

    string ret;
    for (string row : rows) {
    ret += row;
    }

    return ret;
    }
    };

  • 相关阅读:
    xml解析
    File
    IO操作
    Json解析
    JNI字段描述符
    Android JNI get Context
    快速排序
    Android Scroller与computeScroll的调用机制关系
    Android 更新视图函数ondraw() 和dispatchdraw()的区别
    Android Studio 两个包里的类冲突
  • 原文地址:https://www.cnblogs.com/wtzmz/p/12892460.html
Copyright © 2011-2022 走看看