Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 434745b

Browse files
author
uuk020
committed
数组中由k个连续字符串组成的第一个最长字符串 longestConsec
1 parent c6722f5 commit 434745b

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

‎longestConsec/longestConsec.php

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
<?php
2+
/*
3+
* 返回数组中由k个连续字符串组成的第一个最长字符串。
4+
* You are given an array strarr of strings and an integer k.
5+
* Your task is to return the first longest string consisting of k consecutive strings taken in the array.
6+
* Example: longest_consec(["zone", "abigail", "theta", "form", "libe", "zas", "theta", "abigail"], 2) --> "abigailtheta"
7+
* n being the length of the string array, if n = 0 or k > n or k <= 0 return "".
8+
*
9+
*/
10+
function longestConsec($strarr, $k)
11+
{
12+
$longest = '';
13+
// 减去$k是为了当$i自增到$i-$k时候$j的值不能大于数组长度
14+
for ($i = 0; $i <= count($strarr) - $k; $i++) {
15+
$string = '';
16+
// 循环$k范围, 进行拼接字符串
17+
for ($j = 0; $j < $k; $j++) {
18+
// $i+$j的作用是根据$i的值来依次拼接字符串($j次数).
19+
$string .= $strarr[$i + $j];
20+
}
21+
// 比较字符串长度
22+
if (strlen($string) > strlen($longest)) {
23+
$longest = $string;
24+
}
25+
}
26+
27+
return $longest;
28+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /