C#LeetCode刷題之#345-反轉字串中的母音字母(Reverse Vowels of a String)
阿新 • • 發佈:2018-12-14
問題
編寫一個函式,以字串作為輸入,反轉該字串中的母音字母。
輸入: "hello"
輸出: "holle"
輸入: "leetcode"
輸出: "leotcede"
說明:母音字母不包含字母"y"。
Write a function that takes a string as input and reverse only the vowels of a string.
Given s = "hello", return "holle".
Given s = "leetcode", return "leotcede".
Note:The vowels does not include the letter "y".
示例
public class Program { public static void Main(string[] args) { var s = "holle"; var res = ReverseVowels(s); Console.WriteLine(res); s = "leotcede"; res = ReverseVowels2(s); Console.WriteLine(res); Console.ReadKey(); } private static string ReverseVowels(string s) { //暴力解法 //LeetCode超時未AC //記錄母音字母 var vowels = new List<char>() { 'a','e','i','o','u', 'A','E','I','O','U' }; //字典記錄所有母音字母及位置 var dic = new Dictionary<int, char>(); for(var i = 0; i < s.Length; i++) { if(vowels.Contains(s[i])) { dic[i] = s[i]; } } //兩兩前後交換所有母音值 for(var i = 0; i < dic.Count / 2; i++) { var key1 = dic.ElementAt(i).Key; var key2 = dic.ElementAt(dic.Count - i - 1).Key; var swap = dic[key1]; dic[key1] = dic[key2]; dic[key2] = swap; } //重新規劃母音字串順序 var res = new StringBuilder(s); foreach(var item in dic) { res[item.Key] = item.Value; } //返回結果 return res.ToString(); } private static string ReverseVowels2(string s) { //雙指標法 //記錄母音字母 var vowels = new List<char>() { 'a','e','i','o','u', 'A','E','I','O','U' }; //轉換成 char 陣列 //因為 C# 的字串索引器是隻讀的,所以這是必須的 var chars = s.ToCharArray(); //前後雙指標法 var i = 0; var j = s.Length - 1; //迴圈直到指標碰撞時為止 while(i < j) { //從左向右找到母音字元 while(i < j && !vowels.Contains(chars[i])) i++; //從右向左找到母音字元 while(i < j && !vowels.Contains(chars[j])) j--; //交換它們,注意這裡的條件是必須的 if(i < j) { var swap = chars[i]; chars[i++] = chars[j]; chars[j--] = swap; } } //返回結果 return new string(chars); } }
以上給出2種演算法實現,以下是這個案例的輸出結果:
hello
leetcode
分析:
顯而易見,以上2種演算法的時間複雜度均為: 。