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

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

    Subscribe to see which companies asked this question

    题意挺难懂吧。就是把字符串Z型实现,而且不是ZZ这样,就是纵项和斜项交叉显示。

    刚开始打算直接用string实现,然后寻找下标的关系,但是发现有可能有多个Z

    后来发现我们只需要逐个打印每行,这样用map实现不是很好嘛~!

    所以计算下标的规律就好了。

     1 class Solution {
     2 public:
     3 
     4     string convert(string s, int numRows) {
     5         string result="";
     6         int len=s.length();
     7         if(numRows>=len||numRows==1) return s;
     8         int c=numRows-2;     //斜项的个数
     9         int g=c+numRows;     //一个z需要的个数(因为不是ZZ而是纵项斜项交叉的,所以不是2*numRows+c)
    10         int index=0;
    11         map<int,string> mp;
    12         for(int i=0;i<len;i++){
    13             index=i%g;
    14             if(0<=index&&index<=numRows-1) mp[index]+=s[i];
    15             if(numRows<=index&&index<=numRows+c-1) mp[numRows+c-index]+=s[i];
    16         }
    17         for(auto i=mp.begin();i!=mp.end();i++){
    18             result+=(*i).second;       
    19         }
    20         return result;
    21     }
    22 };
  • 相关阅读:
    判断浏览器是pc端和移动
    高德谷歌地图切换成英文地图
    小程序修改默认的单选框复选框样式
    推荐系统| ① Movies概述
    推荐系统| ② 离线推荐&基于隐语义模型的协同过滤推荐
    数据结构与算法| 复杂度分析
    Flink| 运行架构
    机器学习| 高数-基础
    Flink| 概述| 配置安装
    推荐系统| 概述
  • 原文地址:https://www.cnblogs.com/LUO77/p/5081595.html
Copyright © 2011-2022 走看看