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

反转一个字符串。时间复杂度O(n),空间复杂度O(1)

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:
  1. The string consists of lower English letters only.
  2. 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--]);    }};


原创粉丝点击