题目:Reverse String
Write a function that takes a string as input and returns the string reversed.
Example:
Given s = "hello", return "olleh".
题意:逆置字符串
思路:很简单没什么好说的
string reverseString(string s){ for (int i = 0, j = s.length() - 1; i < j; ++i, --j){ s[i] ^= s[j];//交换 s[j] ^= s[i]; s[i] ^= s[j]; } return s; }
题目:Reverse String II
Example:
Input: s = "abcdefg", k = 2 Output: "bacdfeg"
Restrictions:
- The string consists of lower English letters only.
- Length of the given string and k will in the range [1, 10000]
题意:每长度为k的子串逆置一次。
思路:
也很简单,细心写没什么问题,需要注意的是不足k时的情况,此时也需要逆置。
string reverseStr(string s, int k){ //i,j分别表示2k中前一个k个元素的起始和终止的位置 int i = 0, j = k - 1, t = 2 * k - 1; for (; t < s.length(); t += 2 * k){//t每次前移2k个位置 for (int l = i, r = j; l < r; ++l, --r){ s[l] ^= s[r];//交换 s[r] ^= s[l]; s[l] ^= s[r]; } i = t + 1; j = i + k - 1; } if (j >= s.length())j = s.length() - 1;//不足k时 for (int l = i, r = j; l < r; ++l, --r){ s[l] ^= s[r];//交换 s[r] ^= s[l]; s[l] ^= s[r]; } return s; }
题目: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.
题意:逆置一句话中的每个单词,每个单词使用一个空格隔开。
string reverseWords(string s){ int i = 0, j = 0; while (j < s.length()){ while (j < s.length() && !isspace(s[j]))++j;//找到间隔的空格字符 for (int l = i, r = j - 1; l < r; ++l, --r){ s[l] ^= s[r];//交换 s[r] ^= s[l]; s[l] ^= s[r]; } while (j < s.length() && isspace(s[j]))++j;//跳过连续空格 i = j; } return s; }
题目:Reverse Vowels of a String
Write a function that takes a string as input and reverse only the vowels of a string.
Example 1:
Given s = "hello", return "holle".
Example 2:
Given s = "leetcode", return "leotcede".
Note:
The vowels does not include the letter "y".
题意:逆置一个字符串中的元音字母,其他字母位置不变。
string reverseVowels(string s){ string vowels("aeiouAEIOU"); for (int i = 0, j = s.length() - 1; i < j;){ if (vowels.find(s[i]) == string::npos){ ++i; continue; } else if (vowels.find(s[j]) == string::npos){ --j; continue; } //i和j对应的都是元音字母,则交换 s[i] ^= s[j]; s[j] ^= s[i]; s[i] ^= s[j]; ++i; --j; } return s; }