LeetCode
来源:互联网 发布:淘宝店铺怎么提高流量 编辑:程序博客网 时间:2024/06/17 15:22
344. Reverse String
Write a function that takes a string as input and returns the string reversed.
Example:
Given s = "hello", return "olleh".
class Solution {public: string reverseString(string s) { int i = 0, j = s.length() - 1; while (i < j) { swap(s[i], s[j]); i++; j--; } return s; }};
541. Reverse String II
Given a string and an integer k, you need to reverse the first k characters for every 2k characters counting from the start of the string. If there are less than k characters left, reverse all of them. If there are less than 2k but greater than or equal to k characters, then reverse the first k characters and left the other as original.
Example:
Input: s = "abcdefg", k = 2Output: "bacdfeg"Restrictions:
- The string consists of lower English letters only.
- Length of the given string and k will in the range [1, 10000]
每2k个字符反转前k个。时间复杂度O(n)
class Solution {public: string reverseStr(string s, int k) { int len = s.length(); int loc = 0; int i = 0, j = min(len, k) - 1; while (i < len) { while (i < j) { swap(s[i++], s[j--]); } i = loc + 2 * k; j = min(i + k, len) - 1; loc = i; } return s; }};
557. Reverse Words in a String III
Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order.
Example 1:
Input: "Let's take LeetCode contest"Output: "s'teL ekat edoCteeL tsetnoc"
Note: In the string, each word is separated by single space and there will not be any extra space in the string.
翻转一个句子中的每个单词。时间复杂度O(n)
class Solution {public: string reverseWords(string s) { int pre = 0; for (int i = 0; i < s.length(); ++i) { if (s[i] == ' ') { solve(s, pre, i-1); pre = i+1; } } if (pre < s.length()) solve(s, pre, s.length() - 1); return s; } void solve(string& s, int i, int j) { while (i < j) swap(s[i++], s[j--]); }};
- leetcode
- [leetcode]
- LeetCode
- leetcode
- leetcode
- leetcode:
- leetcode:
- LeetCode
- leetcode
- LEETCODE
- leetcode
- leetCode
- leetcode
- [leetcode]
- LeetCode
- leetcode
- leetcode:
- leetcode
- Java编程思想重点笔记(Java开发必看)
- springboot【17】日志管理之logback
- angularjs1结合ui-router、ocLazyLoad分步按需加载js文件
- 解决ueditor编辑器图片在线管理图片无法显示
- Fragment Can not perform this action after onSaveInstanceState
- LeetCode
- Python 快速入门
- Linux执行ls,会引起哪些系统调用
- java基础之System类
- 装饰(包装)设计模式学习笔记
- Intellij 加载文件 FileNotFoundException 异常处理
- qduoj 帅气的HYC的珍珠(树状数组)
- HDU 6105 (2017 多校训练赛6 1010)Gameia(博弈)
- 博主介绍