Given a string s representing a phrase, return its acronym. Acronyms should be capitalized and should not include the word “and”.
Example 1
Input
s = “For your information”
Output
“FYI”Example 2
Input
s = “National Aeronautics and Space Administration”
Output
“NASA”
Compute the Acronym from a Sentence in C++
Given a String C++, we can use the istringstream to tokenize the words and then skip the “and” and accumulate the first character (in uppercase) for the words.
1 2 3 4 5 6 7 8 9 10 | string solve(string s) { istringstream ss(s); string ans = "", word; while (ss >> word) { if (word != "and") { ans += toupper(word[0]); } } return ans; } |
string solve(string s) { istringstream ss(s); string ans = "", word; while (ss >> word) { if (word != "and") { ans += toupper(word[0]); } } return ans; }
The Acronym is computed using one-pass algorithm. The time complexity is O(N) where N is the size of the given sentence and the space requirement is O(1).
–EOF (The Ultimate Computing & Technology Blog) —
GD Star Rating
loading...
206 wordsloading...
Last Post: In-place Algorithm to Move Zeros to End of List
Next Post: Algorithm to Follow the Instructions to Traversal a Binary Tree