557. Reverse Words in a String III
Дана строка s. Необходимо изменить порядок символов в каждом слове в предложении, сохранив при этом пробелы и начальный порядок слов.
Пример:
Input: s = "Let's take LeetCode contest"
Output: "s'teL ekat edoCteeL tsetnoc"
C# решение
сопоставлено/оригиналpublic class Solution {
public string ReverseWords(string s) {
char[] chars = s.ToCharArray();
int lastSpaceIndex = -1;
int len = chars.Length;
for (int strIndex = 0; strIndex <= len; strIndex++) {
if (strIndex == len || chars[strIndex] == ' ') {
int startIndex = lastSpaceIndex + 1;
int endIndex = strIndex - 1;
while (startIndex < endIndex) {
char temp = chars[startIndex];
chars[startIndex] = chars[endIndex];
chars[endIndex] = temp;
startIndex++;
endIndex--;
}
lastSpaceIndex = strIndex;
}
}
return new string(chars);
}
}
C++ решение
auto-draft, проверить перед отправкой#include <bits/stdc++.h>
using namespace std;
// Auto-generated C++ draft from the C# solution. Review containers, LINQ and helper types before submit.
class Solution {
public:
public string ReverseWords(string s) {
char[] chars = s.ToCharArray();
int lastSpaceIndex = -1;
int len = chars.size();
for (int strIndex = 0; strIndex <= len; strIndex++) {
if (strIndex == len || chars[strIndex] == ' ') {
int startIndex = lastSpaceIndex + 1;
int endIndex = strIndex - 1;
while (startIndex < endIndex) {
char temp = chars[startIndex];
chars[startIndex] = chars[endIndex];
chars[endIndex] = temp;
startIndex++;
endIndex--;
}
lastSpaceIndex = strIndex;
}
}
return new string(chars);
}
}
Java решение
сопоставлено/оригиналpublic class Solution {
public String reverseWords(String s) {
char[] chars = s.toCharArray();
int lastSpaceIndex = -1;
int len = chars.length;
for (int strIndex = 0; strIndex <= len; strIndex++) {
if (strIndex == len || chars[strIndex] == ' ') {
int startIndex = lastSpaceIndex + 1;
int endIndex = strIndex - 1;
while (startIndex < endIndex) {
char temp = chars[startIndex];
chars[startIndex] = chars[endIndex];
chars[endIndex] = temp;
startIndex++;
endIndex--;
}
lastSpaceIndex = strIndex;
}
}
return new String(chars);
}
}
JavaScript решение
сопоставлено/оригиналclass Solution {
reverseWords(s) {
let chars = s.split('');
let lastSpaceIndex = -1;
let len = chars.length;
for (let strIndex = 0; strIndex <= len; strIndex++) {
if (strIndex == len || chars[strIndex] == ' ') {
let startIndex = lastSpaceIndex + 1;
let endIndex = strIndex - 1;
while (startIndex < endIndex) {
let temp = chars[startIndex];
chars[startIndex] = chars[endIndex];
chars[endIndex] = temp;
startIndex++;
endIndex--;
}
lastSpaceIndex = strIndex;
}
}
return chars.join('');
}
}
Python решение
сопоставлено/оригиналclass Solution:
def reverseWords(self, s: str) -> str:
s = list(s)
lastSpaceIndex = -1
length = len(s)
for strIndex in range(length + 1):
if strIndex == length or s[strIndex] == ' ':
startIndex = lastSpaceIndex + 1
endIndex = strIndex - 1
while startIndex < endIndex:
s[startIndex], s[endIndex] = s[endIndex], s[startIndex]
startIndex += 1
endIndex -= 1
lastSpaceIndex = strIndex
return ''.join(s)
Go решение
сопоставлено/оригиналpackage main
import (
"fmt"
)
func reverseWords(s string) string {
chars := []rune(s)
lastSpaceIndex := -1
len := len(chars)
for strIndex := 0; strIndex <= len; strIndex++ {
if strIndex == len || chars[strIndex] == ' ' {
startIndex := lastSpaceIndex + 1
endIndex := strIndex - 1
for startIndex < endIndex {
chars[startIndex], chars[endIndex] = chars[endIndex], chars[startIndex]
startIndex++
endIndex--
}
lastSpaceIndex = strIndex
}
}
return string(chars)
}
func main() {
s := "Let's take LeetCode contest"
fmt.Println(reverseWords(s)) // Output: "s'teL ekat edoCteeL tsetnoc"
}
Algorithm
Создайте переменную lastSpaceIndex и установите её значение в -1. Пройдите по каждому символу строки s от 0-го до n-го индекса, используя указатель strIndex.
Когда strIndex указывает на пробел, определите начало (startIndex = lastSpaceIndex + 1) и конец (endIndex = strIndex - 1) текущего слова. Используя два указателя, измените порядок символов в текущем слове.
Обновите lastSpaceIndex значением strIndex. После окончания цикла измените порядок символов в последнем слове (от lastSpaceIndex + 1 до конца строки).
😎
Вакансии для этой задачи
Показаны активные вакансии с пересечением по тегам задачи.