We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
给你一个字符串text,该字符串由若干被空格包围的单词组成。每个单词由一个或者多个小写英文字母组成,并且两个单词之间至少存在一个空格。题目测试用例保证text至少包含一个单词 。
text
请你重新排列空格,使每对相邻单词之间的空格数目都 相等 ,并尽可能最大化该数目。如果不能重新平均分配所有空格,请 将多余的空格放置在字符串末尾 ,这也意味着返回的字符串应当与原text字符串的长度相等。
返回 重新排列空格后的字符串 。
输入:text = " this is a sentence " 输出:"this is a sentence" 解释:总共有 9 个空格和 4 个单词。可以将 9 个空格平均分配到相邻单词之间,相邻单词间空格数为:9 / (4-1) = 3 个。
输入:text = " practice makes perfect" 输出:"practice makes perfect " 解释:总共有 7 个空格和 3 个单词。7 / (3-1) = 3 个空格加上 1 个多余的空格。多余的空格需要放在字符串的末尾。
输入:text = "hello world" 输出:"hello world"
输入:text = " walks udp package into bar a" 输出:"walks udp package into bar a "
输入:text = "a" 输出:"a"
来源:力扣(LeetCode) 链接:https://leetcode.cn/problems/rearrange-spaces-between-words 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
The text was updated successfully, but these errors were encountered:
就是一个简单的模拟
class Solution { /** * @param String $text * @return String */ function reorderSpaces($text) { $space_count = 0; $word_count = 0; $prefix = ''; $word_array = []; for ($i = 0; $i < strlen($text); $i++) { if ($text[$i] === ' ') { if (isset($word)) { $word_array[] = $word; unset($word); } $space_count++; } else { if (!isset($word)) { $word = $text[$i]; } else { $word .= $text[$i]; } if ($prefix === ' ' || $prefix === '') { $word_count++; } } $prefix = $text[$i]; } if (isset($word)) { $word_array[] = $word; } if ($word_count === 1) { return $word_array[0] . ($space_count === 0 ? '' : str_pad(' ', $space_count)); } $interval_sapce_count = intval($space_count/($word_count-1)); $result = implode(str_pad(' ', $interval_sapce_count), $word_array); if ($space_count%($word_count-1) > 0) { $result .= str_pad(' ', $space_count%($word_count-1)); } return $result; } }
Sorry, something went wrong.
No branches or pull requests
给你一个字符串
text
,该字符串由若干被空格包围的单词组成。每个单词由一个或者多个小写英文字母组成,并且两个单词之间至少存在一个空格。题目测试用例保证text
至少包含一个单词 。请你重新排列空格,使每对相邻单词之间的空格数目都 相等 ,并尽可能最大化该数目。如果不能重新平均分配所有空格,请 将多余的空格放置在字符串末尾 ,这也意味着返回的字符串应当与原
text
字符串的长度相等。返回 重新排列空格后的字符串 。
示例 1:
示例 2:
示例 3:
示例 4:
示例 5:
提示:
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/rearrange-spaces-between-words
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
The text was updated successfully, but these errors were encountered: