这可能是一个小面试题,给定字符串abbcccdeeet,包含了连续的字符,要求将字符串压缩成a1b2c3d1e3t1。
函数实现
function Compress-String([string]$string)
{
# argument validation
if($string.Length -eq 0)
{
return [string]::Empty
}
# temp character
$ch = $string[0]
# the count of current character
$count = 1
# current index
$i=0
# string to append result
$result = New-Object System.Text.StringBuilder
while($i -lt $string.Length)
{
$count = 0
# loop until find different character
while($string[$i] -eq $ch)
{
$count ++
$i++
}
# append result
$result.AppendFormat("{0}{1}",$ch, $count) | Out-Null
# swap temperary character
$ch=$string[$i]
}
return $result.ToString()
}
测试用例
# test case 1 Compress-String $null # test case 2 Compress-String '' # test case 3 Compress-String -string 'abc' # test case 4 Compress-String -string 'abbcccdeeet'
输出
本文链接: https://www.pstips.net/compress-string.html
请尊重原作者和编辑的辛勤劳动,欢迎转载,并注明出处!
请尊重原作者和编辑的辛勤劳动,欢迎转载,并注明出处!
