最近做了一下
Coderbyte的免费算法,因第一次做算法题目,现把自己的思路写出来,以便自己以后回顾。如果能帮到一些志同道合的朋友就更好了。如果此系列文章有误,还望指出;欢迎讨论,互相学习进步。
ps:另为了避免翻译出错,算法题目的要求直接就用网上原文,这里不再进行翻译了;所有算法用c#完成,如有不便,敬请谅解。
Challenge
Using the C# language, have the function
LongestWord(sen) take the
sen parameter being passed and return the largest word in the string. If there are two or more words that are the same length, return the first word from the string with that length. Ignore punctuation and assume
sen will not be empty.
Sample Test Cases
Input:"fun&!! time"
Output:"time"
Input:"I love dogs"
Output:"love"
Longest Word算法大致意思是找出字符串里面最长的单词,并返回。
public static string LongestWord(string sen)
{
List<string> Wordslist = new List<string>();
List<char> chlist = new List<char>();
int MaxLength = 0;
int MaxIndex = -1;
char ch = '\0';
int count = sen.Length;
bool IsWorld;//true-是一个单词
/*
* 整体思路:判断每次字符,提取里面正确的单词并添加到Wordslist集合
*/
for (int i = 0; i < count; i++)
{
ch = sen[i];
if ((ch >= 'a' && ch <= 'z')
|| (ch >= 'A' && ch <= 'Z')
|| (ch >= '0' && ch <= '9')/*刚开始没有判断数字的,但是测试例子里面有数字,只能加上了*/)
{
chlist.Add(ch);
IsWorld = i == count - 1;//最后一个字符代表一个单词结束
}
else
{
IsWorld = true;
}
if (IsWorld)
{
if (chlist.Count > 0)
{
Wordslist.Add(new string(chlist.ToArray()));
if (Wordslist[Wordslist.Count - 1].Length > MaxLength)
{
MaxLength = Wordslist[Wordslist.Count - 1].Length;
MaxIndex = Wordslist.Count - 1;
}
chlist.Clear();
}
}
}
return (MaxIndex > -1) ? Wordslist[MaxIndex] : sen;
}