Problem overview
The function amazingToNotAmazing receives a word s that starts with a lower-case a. It returns the text "not ", including the space, followed by the word without its first character. That turns "amazing" into "not mazing".
Only the first character is removed. For "aMAZING" the answer is "not MAZING": the other letters keep their case. For "an" the answer is "not n", since removing the a leaves a single letter.
Approach
There are two things to do. First, drop the first character of the word. Second, put a fixed piece of text in front of what is left. Neither needs a loop or a condition: the word is guaranteed to start with a, so the function can remove the first character without checking it.
In C++, substr gives a new string made from part of an existing one. When you pass it only a start position, it takes everything from that position to the end. Starting at index 1 therefore skips exactly the first character.
Step by step
- Cut off the first character.
s.substr(1)starts at index 1 and runs to the end of the string, so it is the word without its first letter. - Put
"not "in front. The space is part of the text inside the quotes. Without it,"amazing"would turn into"notmazing". - Return the joined string. The whole function is one
returnstatement.
The solution in C++
class Solution {
public:
string amazingToNotAmazing(string s) {
return "not " + s.substr(1);
}
};
Some C++ details about this one line:
- Joining a literal and a string. The text
"not "is a string literal, which is an array of characters, not astd::string. The+operator works here because the other operand,s.substr(1), is astd::string, and C++ defines+for a literal and a string. Two literals can't be added:"not " + "mazing"doesn't compile, because there is no+between two character arrays. - The result is a new string.
substrcopies the characters it selects, sositself isn't modified. The function receivessby value anyway. - The upper bound of
substr. A start position equal to the length of the string is allowed and gives an empty string. A start position greater than the length throwsstd::out_of_range.
Edge cases and common mistakes
- Forgetting the space.
"not" + s.substr(1)gives"notmazing". The space must be inside the quotes. - Starting at index 0.
s.substr(0)is the whole word, so the result would be"not amazing". The first character is at index 0, so the piece to keep starts at 1. - Changing the case. The task only removes the first character. Letters that are already upper case stay upper case, so there is nothing to convert.
- A word of one character. If the word were just
"a",s.substr(1)would return an empty string and the answer would be"not ". The lesson's words have at least two characters, so the result always has something after the space.
Testing
"amazing"gives"not mazing"."aMAZING"gives"not MAZING"."an"gives"not n".
