經典面試題,考察迴圈控制、字符串拼接、空間想像。提供三種風格實現:雙層迴圈、字符串重複、單迴圈數學法。
function triangleLoop(int $rows, string $char = '*'): void {
for ($i = 1; $i <= $rows; $i++) {
// 打印空格
for ($s = 1; $s <= $rows - $i; $s++) echo ' ';
// 打印字符 (2*i-1 個)
for ($c = 1; $c <= 2 * $i - 1; $c++) echo $char;
echo "\n";
}
}
function triangleStrRepeat(int $rows, string $char = '*'): void {
for ($i = 1; $i <= $rows; $i++) {
echo str_repeat(' ', $rows - $i);
echo str_repeat($char, 2 * $i - 1);
echo "\n";
}
}
function triangleMath(int $rows, string $char = '*'): void {
$width = 2 * $rows - 1;
$mid = $rows - 1; // 中心列索引 (0-based)
for ($row = 0; $row < $rows; $row++) {
$line = '';
for ($col = 0; $col < $width; $col++) {
// 判斷是否在三角形範圍內
if (abs($col - $mid) <= $row) $line .= $char;
else $line .= ' ';
}
echo $line . "\n";
}
}
* *** ***** ******* *********
// 方法一: 0.45s // 方法二: 0.12s (str_repeat 內核優化) // 方法三: 0.38s
推薦方法二,代碼簡潔且效能最優。
function triangleHtml(int $rows, string $char = '*', string $space = ' '): string {
$html = '';
for ($i = 1; $i <= $rows; $i++) {
$html .= str_repeat($space, $rows - $i);
$html .= str_repeat($char, 2 * $i - 1);
$html .= "
\n";
}
return $html;
}
echo triangleHtml(5);