只是为了好玩,我读了these面试题,试图在C#和F#中找到解决方案,而我却在习惯性F#中努力遵循以下要求而又不改变布尔值或使用正则表达式:
为您提供了包含一个或多个$符号的单词字符串,例如: “ foo bar foo $ bar $ foo bar $” 问题:如何从给定的字符串中删除$的第二次和第三次出现?
我的强制性F#解决方案出现突变:
let input = "foo bar foo $ bar $ foo bar $ "
let sb = new StringBuilder()
let mutable first = true
let f c=
if c='$' && first then first<-false
else sb.Append(c) |> ignore
input |> Seq.iter f
(还有C#):
var input = "foo bar foo $ bar $ foo bar $ ";
var sb = new StringBuilder();
bool first = true;
input.ForEach(c => {
switch (c)
{
case '$' when first: first = false; break;
default: sb.Append(c);break;
};
});
答案 0 :(得分:3)
let f (s:string) =
s.Split('$')
|> Array.toList
|> function
| [] -> ""
| [ a ] -> a
| [ a; b ] -> a + "$" + b
| a :: b :: c :: rest -> a + "$" + b + c + (rest |> String.concat "$")
f "foo bar foo $ bar $ foo bar $ "
// "foo bar foo $ bar foo bar "
f "1 $ 2 $ 3 $ 4 $ 5 $"
//"1 $ 2 3 4 $ 5 $"
请注意,此解决方案仅删除$
的第二个和第三个实例。如果要删除除第一个以外的所有内容,则将String.concat "$"
替换为String.concat ""
答案 1 :(得分:3)
let f (s:string) =
s.Split('$')
|> Seq.mapi (fun i t -> (if i > 3 || i = 1 then "$" else "") + t)
|> String.concat ""
这是另一个使用 tail 递归和char
计算表达式扫描每个seq
的人:
let f (s:string) =
let rec chars n input = seq {
match Seq.tryHead input with
| Some '$' -> if not(n = 1 || n = 2) then yield '$'
yield! Seq.tail input |> chars (n+1)
| Some c -> yield c
yield! Seq.tail input |> chars n
| None -> ()
}
chars 0 s
|> fun cs -> new string(Seq.toArray cs)
它可能更长一些,但可能比第一个更有效。
编辑:不,它不是更有效,也不是尾部递归,可能是因为它发生在计算表达式内。