题目
The goal of this exercise is to convert a string to a new string where each character in the new string is “(” if that character appears only once in the original string, or “)” if that character appears more than once in the original string. Ignore capitalization when determining if a character is a duplicate.
Examples
"din" => "((("
"recede" => "()()()"
"Success" => ")())())"
"(( @" => "))(("
Notes
Assertion messages may be unclear about what they display in some languages. If you read “…It Should encode XXX”, the “XXX” is the expected result, not the input!
代码
using System;
using System.Collections.Generic;
using System.Text;
public class Kata
{
public static string DuplicateEncode(string word)
{
//题目说不区分大小写,所以需要将大写变小写
string s =word.ToLower();
//统计每个字符出现的次数,存在字典里
var dict =new Dictionary<char,int>();
for(int i=0;i<s.Length;i++){
char c=s[i];
if(!dict.ContainsKey(c)){dict.Add(c,1);}
else{dict[c]++;}
}
//遍历给定的字符串,查看其中每一项字符c在字典里存的次数
//创建一个stringbuilder用来存放替换后的字符
StringBuilder sb=new StringBuilder();//stringbuilder是个类,所以这样调用
for(int i=0;i<s.Length;i++){
char c=s[i];
if(dict[c]==1){sb.Append('(');}
else{sb.Append(')');}
}
return sb.ToString();
}
}