返回
算法实战:重新排列单词间空格的模拟解法
后端
2024-01-03 03:28:26
算法的世界里,模拟题就像一场益智游戏,考验着我们的思维敏捷度和对细节的关注。今天,我们挑战的是 LeetCode 上的 1592. 重新排列单词间的空格。
题目简介
这是一道简单的模拟题,要求我们给定一个字符串 s
,重新排列字符串中的单词,单词间仅用一个空格隔开。
模拟解法
模拟解法的精髓在于逐个字符地处理输入字符串,并根据给定的规则对字符进行操作。本题中,我们需要将单词从字符串中提取出来,然后重新排列并添加空格。
Python 代码示例
def reorderSpaces(s):
"""
:type s: str
:rtype: str
"""
# 提取单词和空格
words = s.split()
spaces = len(s) - sum(len(word) for word in words)
# 处理边界情况:没有单词或只有一个单词
if not words or len(words) == 1:
return s
# 计算每个单词之间的空格数
spaces_between_words = spaces // (len(words) - 1)
extra_spaces = spaces % (len(words) - 1)
# 重新排列单词并添加空格
result = ""
for word in words:
result += word + " " * spaces_between_words
# 添加额外的空格
result += " " * extra_spaces
# 去除末尾多余的空格
return result.rstrip()
Java 代码示例
public class Solution {
public String reorderSpaces(String s) {
String[] words = s.split(" +");
int spaces = s.length() - words.length;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < words.length; i++) {
sb.append(words[i]);
if (i < words.length - 1) {
int spacesBetweenWords = spaces / (words.length - 1);
int extraSpaces = spaces % (words.length - 1);
if (extraSpaces > 0) {
sb.append(' ');
extraSpaces--;
}
for (int j = 0; j < spacesBetweenWords; j++) {
sb.append(' ');
}
}
}
return sb.toString();
}
}
C++ 代码示例
class Solution {
public:
string reorderSpaces(string s) {
vector<string> words;
int spaces = 0;
stringstream ss(s);
string word;
while (ss >> word) {
words.push_back(word);
spaces += count(word.begin(), word.end(), ' ');
}
if (words.size() == 1) {
return s;
}
int spacesBetweenWords = spaces / (words.size() - 1);
int extraSpaces = spaces % (words.size() - 1);
string result;
for (int i = 0; i < words.size(); i++) {
result += words[i];
if (i < words.size() - 1) {
for (int j = 0; j < spacesBetweenWords; j++) {
result += ' ';
}
if (extraSpaces > 0) {
result += ' ';
extraSpaces--;
}
}
}
return result;
}
};
JavaScript 代码示例
/**
* @param {string} s
* @return {string}
*/
const reorderSpaces = (s) => {
const words = s.split(" ");
const spaces = s.length - words.join("").length;
if (words.length === 1) {
return s;
}
const spacesBetweenWords = Math.floor(spaces / (words.length - 1));
const extraSpaces = spaces % (words.length - 1);
let result = "";
for (let i = 0; i < words.length; i++) {
result += words[i];
if (i < words.length - 1) {
for (let j = 0; j < spacesBetweenWords; j++) {
result += " ";
}
if (extraSpaces > 0) {
result += " ";
extraSpaces--;
}
}
}
return result.trim();
};
总结
通过使用模拟解法,我们可以有效地处理 LeetCode 上的 1592. 重新排列单词间的空格 题目。这种方法不仅简单易懂,而且适用于各种语言。只要逐个字符地处理输入字符串,并根据规则操作字符,我们就能够轻松解决这类模拟题。