要求:
- 设计一个算法从一片英语文章或者英语字符串里面输出其中最长的单词.
Input: string Output: string
- 尽可能多的设计测试用例来测试这个算法.
- 考虑空间和时间复杂度看作是一个加分项
Version1.0
1 using System; 2 3 namespace GetLongestWord 4 { 5 class Program 6 { 7 static void Main(string[] args) 8 { 9 Console.WriteLine("Please input a string:"); 10 //string inputString = "Hello Shanghai Nice To meet you guys"; 11 string inputString = Console.ReadLine(); 12 Program p = new Program(); 13 Console.WriteLine("The longest word is : {0}", p.GetLongestWord(inputString)); 14 Console.WriteLine("The length of the longest word is: {0}", p.GetLongestWord(inputString).Length); 15 Console.ReadKey(); 16 } 17 18 string GetLongestWord(string inputString) 19 { 20 int maxLength = 0; 21 int wordLength = 0; 22 int p = 0; 23 for (int i = 0; i < inputString.Length; i++) 24 { 25 if (inputString[i] != ' ') 26 { 27 wordLength++; 28 29 if (maxLength < wordLength) 30 { 31 maxLength = wordLength; 32 p = i + 1 - wordLength; 33 } 34 } 35 else 36 { 37 wordLength = 0; 38 } 39 } 40 41 string longestWord = ""; 42 for (int i = 0, m = p; i < maxLength; i++, m++) 43 { 44 longestWord = longestWord + inputString[m]; 45 } 46 47 return longestWord; 48 } 49 } 50 }