这不是家庭作业:在处理 PHP 字符串差异和动态限制时遇到这种情况
给定一串n
单词,如何在m
不改变单词序列的情况下将它们分成组?
Example 1:
String: "My name is SparKot"
Groups: 2 (string is split in to two strings)
Possible groups will be:
('My', 'name is SparKot'),
('My name', 'is SparKot'),
('My name is', 'SparKot')
用相同的字符串
Example 2:
String: "My name is SparKot"
Groups: 3 (string will be split in to three strings)
Possible groups will be:
('My', 'name', 'is SparKot'),
('My', 'name is', 'SparKot'),
('My name', 'is', 'SparKot')
我的 PHP 函数()没有方向(假设返回多维组):
function get_possible_groups ($orgWords, $groupCount, &$status) {
$words = explode (' ', $orgWords);
$wordCount = count($words);
if ($wordCount < $groupCount) {
$status = -1;
return;
} else if ($wordCount === $groupCount) {
$status = 0;
return (array_chunk($words, 1));
}
for ($idx =0; $idx < $wordCount; $idx) {
for ($jdx =0; $jdx < $groupCount; $jdx++) {
}
}
// append all arrays to form multidimension array
// return groupings[][] array
}
$status =0;
$groupings = get_possible_groups('My name is SparKot', 4, $status);
var_dump($groupings);
对于上面的 example-2 函数应该返回:
$groupings = array (
array ('My', 'name', 'is SparKot'),
array ('My', 'name is', 'SparKot'),
array ('My name', 'is', 'SparKot'));
任何解决此问题的提示将不胜感激。
进步:
- 案例:当
wordCount = groupCount
[解决]