博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode - ZigZag Conversion
阅读量:5167 次
发布时间:2019-06-13

本文共 2339 字,大约阅读时间需要 7 分钟。

2013.12.1 21:48

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   NA P L S I I GY   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:

1 string convert(string text, int nRows);

convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR".

Solution:

  This kind of problem is not complicated, and can be done with some calculation on the scratch before you start coding. Still, special cases need special handlings:

    1. the string is empty

    2. nRows = 1

  Time complexity is O(n), where n is the length of the string. Space complexity is O(n) with the use of char array during the algorithm.

Accepted code:

1 //1RE, 1AC, special case needs special handling 2 class Solution { 3 public: 4     string convert(string s, int nRows) { 5         // IMPORTANT: Please reset any member data you declared, as 6         // the same Solution instance will be reused for each test case.     7          8         // 1RE here, ignored the special case where nRows == 1 9         if(nRows == 1){10             return s;11         }12         char *str = nullptr;13         int i, j, k, len;14         15         len = s.length();16         str = new char[s.length() + 1];17         j = 0;18         for(k = 0; k < nRows; ++k){19             if(k == 0){20                 for(i = 0; i < len; ++i){21                     if(i % (2 * nRows - 2) == 0){22                         str[j++] = s[i];23                     }24                 }25             }else if(k == nRows - 1){26                 for(i = 0; i < len; ++i){27                     if(i % (2 * nRows - 2) == nRows - 1){28                         str[j++] = s[i];29                     }30                 }31             }else{32                 for(i = 0; i < len; ++i){33                     if(i % (2 * nRows - 2) == k || i % (2 * nRows - 2) == 2 * nRows - 2 - k){34                         str[j++] = s[i];35                     }36                 }37             }38         }39         str[j] = 0;40         41         string res = string(str);42         delete[] str;43         return res;44     }45 };

 

转载于:https://www.cnblogs.com/zhuli19901106/p/3453009.html

你可能感兴趣的文章
Java计算两个程序运行时间
查看>>
用C读取INI配置文件
查看>>
描述字符串写入文件
查看>>
maven中properties标签定义变量
查看>>
Android简单逐帧动画Frame的实现(二)
查看>>
四人团-江南行-在乌镇西栅旅游
查看>>
跨域cookie使用
查看>>
安装 Git 并连接 Github
查看>>
Java Client/Server 基础知识
查看>>
泛函分析历史
查看>>
遇见喜欢数学的女孩
查看>>
2017-2018-1 实变函数
查看>>
HDOJ-2153
查看>>
Redis初识
查看>>
QT加载qss
查看>>
委托链
查看>>
c# 后台异步请求接口
查看>>
AI自主决策——有限状态机
查看>>
C#使用Command将dataGrideView表格内数据与数据库交互
查看>>
设计模式 - 单列模式
查看>>