[英]Find the first non-repeated character in a string using C#
I am working to solve this problem. 我正在努力解决这个问题。 I have to find the first nonrepeated character in a string.
我必须找到字符串中的第一个非重复字符。
For example, Input : “teeter” Output: r 例如,输入:“跷跷板”输出:r
I am going to first use HashTables : 我将首先使用HashTables:
class Program
{
static void Main()
{
var inputString = “teeter” ;
Hashtable hashtable = new Hashtable();
int numb = 1;
for (int i=0; i< inputString.length(); i++)
{
if (!hashtable.ContainsKey(hashtable[i]))
hashtable.Add(hashtable[i], numb);
else
hashtable[hashtable[i]] = hashtable[i].Value+ 1 ;
}
}
}
Can I solve this problem using LinQ: 我可以使用LinQ解决此问题吗:
numb = inputString.First(1 == inputString.Where(item =>
item == hashtable[i]).Count());
My questions are : 我的问题是:
-I have to solve this problem using LINQ and using HashTables or Dictionaries. -我必须使用LINQ和HashTables或Dictionaries解决此问题。 Does my solutions ture ?
我的解决方案有效吗?
// throws an ArgumentNullException if s is null.
// throws an InvalidOperationException if there is no non repeating character.
char FirstNonRepeater(string s)
{
return s.ToLookup(c => c).First(g => g.Count() == 1).Key;
}
I don't think you need HashTable
at all. 我认为您根本不需要
HashTable
。 Because string
implements IEnumerable<char>
you can use LINQ directly on your input string: 因为
string
实现IEnumerable<char>
您可以直接在输入字符串上使用LINQ:
var letter = input.GroupBy(x => x).First(g => g.Count() == 1).Key;
Getting back to your HashTable
solution. 回到您的
HashTable
解决方案。 You 're not using it correctly. 您没有正确使用它。
HashTable
is not the same as Dictionary
. HashTable
与Dictionary
。 It does not have key
/ value
, it just has key
s. 它没有
key
/ value
,只有key
s。 You're looking for Dictionary
here: 您在这里寻找
Dictionary
:
var inputString = "teeter";
var dict = new Dictionary<char, int>();
int numb = 1;
for (int i=0; i< inputString.length(); i++)
{
if (!dict.ContainsKey(inputString[i]))
dict.Add(inputString[i], numb);
else
dict[inputString[i]] += 1;
}
For a solution without HashTables, Dictionaries or LINQ, just remove duplicate characters from the string: 对于没有HashTables,Dictionary或LINQ的解决方案,只需从字符串中删除重复的字符:
while (s.IndexOf(s[0], 1) != -1) {
s = s.Replace(s[0].ToString(), "");
}
char result = s[0];
You can check which characters are occured only once, and take first one out of these. 您可以检查哪些字符仅出现一次,然后从中选取第一个。
var inputString = “teeter” ;
var output = inputString.GroupBy(x=>x).FirstOrDefault(x=>x.Count() ==1).Key;
class Program
{
public static void Main(string[] args)
{
Console.WriteLine(FirstNonRepeated("tether"));
Console.ReadKey();
}
public static char? FirstNonRepeated(string word)
{
char[] chararray= word.ToCharArray();
Hashtable hashtable=new Hashtable();
foreach (var c in chararray)
{
if (hashtable.ContainsKey(c))
{
hashtable[c]=(int)hashtable[c]+1;
}
else
{
hashtable.Add(c,1);
}
}
foreach (var v in chararray)
{
if ((int) hashtable[v] == 1)
{
return v;
}
}
return null;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.