6. ZigZag Conversion
来源:互联网 发布:自学编程先看什么书 编辑:程序博客网 时间:2024/06/10 12:55
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:
string convert(string text, int nRows);
convert(“PAYPALISHIRING”, 3) should return “PAHNAPLSIIGYIR”.
这题很简单,主要就是找到位置变化的规律,不涉及什么典型算法或者数据结构。
方法一:时间O(n), 空间O(n)
建立一个vector< string>, 将输入string里每一个char依次放入对应的行中。基本规律就是,插入具有重复性,每隔2*numRows - 2 重复一遍。
代码:
string convert(string s, int numRows) { vector<string> ans(numRows); if (s.size() == 0 || numRows <= 1) return s; int i = 0, j = 0; while (i < s.size()) { if (j < numRows) { ans[j++].push_back(s[i++]); } else if (j < 2 * numRows - 2){ ans[2 * numRows - 2 - j].push_back(s[i++]); j++; } else { j = 0; } } string res; for (i = 0; i < numRows; i++) { res += ans[i]; } return res;}
方法二:时间O(n), 空间O(1)
不用将每行保存,直接在原string上按顺序找到对应元素。
代码:
string convert(string s, int numRows) { if (s.size() == 0 || numRows == 1) return s; string ans = ""; int i = 0, j = 0; int jump = 2 * numRows - 2; while (j < numRows) { i = j; while (i < s.size()) { ans += s[i]; i += jump; if (j != 0 && j != numRows - 1 && i - 2 * j < s.size()) { ans += s[i - 2 * j]; } } j++; } return ans;}
阅读全文
0 0
- LeetCode 6. ZigZag Conversion
- LeetCode --- 6. ZigZag Conversion
- LeetCode 6.ZigZag Conversion
- [Leetcode] 6. ZigZag Conversion
- 6.ZigZag Conversion
- 6. ZigZag Conversion
- 6. ZigZag Conversion
- 【leetcode】6. ZigZag Conversion
- 6.ZigZag Conversion
- 6. ZigZag Conversion
- 6.ZigZag Conversion
- [LeetCode] 6.ZigZag Conversion
- LeetCode - 6. ZigZag Conversion
- 6. ZigZag Conversion
- 6. ZigZag Conversion
- 6.ZigZag Conversion(93.10%)
- 6. ZigZag Conversion
- [leetcode] 6. ZigZag Conversion
- RecyclerView 与 ScrollView嵌套
- ajax发送异步请求(四步操作)
- 最简单的方式用C表示摄氏温度和华氏温度的转换
- ubuntu16.04开启telnet服务
- org.springframework.web.filter.DelegatingFilterProxy
- 6. ZigZag Conversion
- Ubuntu 16.04设置root用户登录图形界面
- [Leetcode][python]Partition List
- Linux CentOS7下安装Zookeeper-3.4.10服务(最新)
- python @,@staticmethod,@classmethod
- Java泛型详解
- C++中的explicit关键字
- 190. Reverse Bits
- 从零基础认识maven工程构建