StringBuilder V
One more problem which is simple but leads to TLE if you use String instead of StringBuilder. The entire code below was initially written with String and I got several time-limit exceeded errors. Switching most of the implementation to StringBuilder solved the problem. Code is down below, cheers, ACC.
You are given a string s consisting of lowercase English words, each separated by a single space.
Determine how many vowels appear in the first word. Then, reverse each following word that has the same vowel count. Leave all remaining words unchanged.
Return the resulting string.
Vowels are 'a', 'e', 'i', 'o', and 'u'.
Example 1:
Input: s = "cat and mice"
Output: "cat dna mice"
Explanation:
- The first word
"cat"has 1 vowel. "and"has 1 vowel, so it is reversed to form"dna"."mice"has 2 vowels, so it remains unchanged.- Thus, the resulting string is
"cat dna mice".
Example 2:
Input: s = "book is nice"
Output: "book is ecin"
Explanation:
- The first word
"book"has 2 vowels. "is"has 1 vowel, so it remains unchanged."nice"has 2 vowels, so it is reversed to form"ecin".- Thus, the resulting string is
"book is ecin".
Example 3:
Input: s = "banana healthy"
Output: "banana healthy"
Explanation:
- The first word
"banana"has 3 vowels. "healthy"has 2 vowels, so it remains unchanged.- Thus, the resulting string is
"banana healthy".
Constraints:
1 <= s.length <= 105sconsists of lowercase English letters and spaces.- Words in
sare separated by a single space. sdoes not contain leading or trailing spaces.
public string ReverseWords(string s)
{
string[] words = s.Split(' ');
int countVowels = CountVowels_(words[0]);
StringBuilder sb = new StringBuilder(s.Length);
sb.Append(words[0]);
for (int i = 1; i < words.Length; i++)
{
sb.Append(" ");
if (countVowels == CountVowels_(words[i]))
{
sb.Append(Reverse_(words[i]));
}
else
{
sb.Append(words[i]);
}
}
return sb.ToString();
}
private string Reverse_(string str)
{
StringBuilder sbRetVal = new StringBuilder(str);
int left = 0;
int right = str.Length - 1;
while (left < right)
{
sbRetVal[left] = str[right];
sbRetVal[right] = str[left];
left++;
right--;
}
return sbRetVal.ToString();
}
private int CountVowels_(string str)
{
int count = 0;
for (int i = 0; i < str.Length; i++)
{
if (str[i] == 'a' ||
str[i] == 'e' ||
str[i] == 'i' ||
str[i] == 'o' ||
str[i] == 'u') count++;
}
return count;
}

Comments
Post a Comment