zoukankan      html  css  js  c++  java
  • 【leetcode】6. ZigZag Conversion

    @requires_authorization
    @author johnsondu
    @create_time 2015.7.10 10:35
    @url https://leetcode.com/problems/zigzag-conversion/
    /**
     * 对于此题,仅仅须要找出相应的字母所在的编号与Z型编码的关系。
     * 对于第一行和最后一行进行单处处理。
     * 而对中间的numRows-2行。则分奇数列和偶数列进行推导。
     * 奇数列从下往上,偶数列从上往下。

    * 时间复杂度(O(n)) * 空间复杂度(O(1)) */ class Solution { public: string convert(string s, int numRows) { // return if numRows == 1 if(numRows < 2) return s; string ans = ""; int len = s.size(); int idx = 0; // Process the first line while(idx < len){ ans = ans + s[idx]; idx = idx + (numRows-1) * 2; } // Process 2-numRows line for(int i = 1; i < numRows - 1; i ++) { // flag: Distinguish the odd and the even column bool flag = false; idx = i; if(idx >= len) break; ans += s[i]; while(idx <= len){ if(!flag) { idx = idx + (numRows - i - 1) * 2; if (idx < len) ans += s[idx]; flag = true; } else{ idx = idx + i * 2; if(idx < len) ans += s[idx]; flag = false; } } } // Process the last line idx = numRows - 1; while(idx < len){ ans = ans + s[idx]; idx = idx + (numRows - 1) * 2; } return ans; } };

  • 相关阅读:
    u Calculate e
    Elevator
    骑士走棋盘
    Number Sequence
    老鼠走迷宫
    Let the Balloon Rise
    A+B Problem II
    Three-Color Flag
    Noldbach problem
    Almost Prime
  • 原文地址:https://www.cnblogs.com/mengfanrong/p/5192782.html
Copyright © 2011-2022 走看看