557. 反转字符串3 Reverse Words in a String III
- Total Accepted: 11103
- Total Submissions: 17987
- Difficulty: Easy
- Contributors:
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.
public class Solution {public string ReverseWords(string s) {char[] cArr = s.ToCharArray();int left = 0;for (int i = 0; i < cArr.Length; i++) {if (cArr[i] == ' ' || i == cArr.Length - 1) {int right = i == cArr.Length - 1 ? i : i - 1;while (left < right) {Swap(left, right, cArr);left++;right--;}i++;left = i;right = i;}}return new String(cArr);}public void Swap(int i, int j, char[] cArr) {char c = cArr[i];cArr[i] = cArr[j];cArr[j] = c;}}

浙公网安备 33010602011771号