publicclassSolution { publicstringMergeAlternately(string word1, string word2) { string ans = ""; int n = word1.Length >= word2.Length ? word1.Length : word2.Length; // 取最大值 for(int i = 0; i < n; i++) { // 交替合并,如果没到字符串尾就继续添加 if(i < word1.Length) ans += word1[i]; if(i < word2.Length) ans += word2[i]; }
return ans; } }
官方解:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
publicclassSolution { publicstringMergeAlternately(string word1, string word2) { int m = word1.Length, n = word2.Length; int i = 0, j = 0;
StringBuilder ans = new StringBuilder(); while (i < m || j < n) { if (i < m) { ans.Append(word1[i]); ++i; } if (j < n) { ans.Append(word2[j]); ++j; } } return ans.ToString(); } }
int gcd = GCD(str1.Length, str2.Length); return str1.Substring(0, gcd); }
// 计算 a, b 的最大公约数,也就是计算两个字符串的长度的最大公约数 privateintGCD(int a ,int b) { return b == 0 ? a: GCD(b, a % b); } }
1431. 拥有最多糖果的孩子
Note
有 n 个有糖果的孩子。给你一个数组 candies,其中 candies[i] 代表第 i 个孩子拥有的糖果数目,和一个整数 extraCandies 表示你所有的额外糖果的数量。
返回一个长度为 n 的布尔数组 result,如果把所有的 extraCandies 给第 i 个孩子之后,他会拥有所有孩子中 最多 的糖果,那么 result[i] 为 true,否则为 false。
注意,允许有多个孩子同时拥有 最多 的糖果数目。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
publicclassSolution { public IList<bool> KidsWithCandies(int[] candies, int extraCandies) { IList<bool> boolList = new List<bool>(); // 找到最大值 int max = candies[0]; foreach (var x in candies) { if (x > max){ max = x; } } // 判断是否有效 foreach (var x in candies) { boolList.Add(x + extraCandies >= max); } return boolList; } }
publicclassSolution { privateboolisVowel(char c) // 判断是否为元音字母 { return c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' || c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U'; } publicstringReverseVowels(string s) { // 遍历两遍,出栈再入栈 Stack<char> charStack = new Stack<char>(); string result = ""; for (int i = 0; i < s.Length; i++) { if (isVowel(s[i])) { charStack.Push(s[i]); } } for (int i = 0; i < s.Length; i++) {
if (isVowel(s[i])) { result += charStack.Pop(); } else { result += s[i]; } } return result; } }
publicclassSolution { publicstringReverseVowels(string s) { int n = s.Length; char[] arr = s.ToCharArray(); int i = 0, j = n - 1; while (i < j) { while (i < n && !IsVowel(arr[i])) { ++i; } while (j > 0 && !IsVowel(arr[j])) { --j; } if (i < j) { Swap(arr, i, j); ++i; --j; } } returnnewstring(arr); }
publicclassSolution { publicstringReverseWords(string s) { Stack<string> wordStack = new Stack<string>(); string word = ""; for (int i = 0; i < s.Length; i++) { if (s[i] == ' ') {
if (word.Length > 0) { Console.WriteLine(word); wordStack.Push(word); word = ""; } } else { word += s[i]; } } wordStack.Push(word);
string ans = ""; while(wordStack.Count > 0) { if (ans.Length > 0) { ans += " "; } ans += wordStack.Pop(); } return ans; } }