PowerShell 查找重复最多的字符

输入一串字符,查找重复最多的字符,输出该字符及重复次数,不排除有多个重复次数并列最多的情况

这是一道普通的面试题,闲的没事,用powershell 试了试

1.下面这种是用map实现的

[CmdletBinding()]
param(
    [ValidateNotNullOrEmpty()]
    [String]$str
)

function main{

$max = 0
$map = @{}
[String]$maxzu

foreach($c in $str.ToCharArray()){
    if(!$map.ContainsKey($c)){
        $chus=1
        $map.Add($c,$chus)
        if($chus -ge $max){
            $maxzu=$maxzu+$c
            $max=$chus
        }
    }else{
        $count = $map.$c
        $count++
        if($count -gt $max){
            $maxzu=$null
            $maxzu=$maxzu+$c
            $max =$count
        }elseif($count -eq $max){
            $maxzu=$maxzu+$c
        }
        $map.$c=$count
    }
}
    $maxzu
    $max
}
main

2.后来又试了试递归,好久不写都忘了,有多个并列的就不好使了

[CmdletBinding()]
param(
    [ValidateNotNullOrEmpty()]
    [String]$str
)

function find($s,$l,$m,$v){

    if($l -eq 1){
        $max=$m
        $value=$v
        $max
        $value
        break
        }
    
    if($s[$l-1] -ne $v){

        $cnt=1;
        [int]$i=$l-2
        for($i;$i -ge 0;$i--){
            if($s[$i] -eq $s[$l-1]){$cnt++}
            if($m -lt $cnt){
                $m=$cnt
                $v=$s[$l-1]
                }
        }
    
    }
    find $s ($l-1) $m $v

}
function main{
    $sttr=$str.ToCharArray()
    $max=1
    $value=$sttr[0]
    if($sttr.Length -eq 1){
        return
    }  
    find $sttr $sttr.Length $max $value
}
main

 

转载于:https://my.oschina.net/qiuSHENv587/blog/3043318

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值