Problem overview
The function repeatLastChar receives a string s and a number n. It returns a new string made of the last character of s, written n times in a row.
For "banana" and n = 3 the last character is 'a', so the answer is "aaa". The last character can be anything: for "Wow!" and n = 2 it is the exclamation mark, and the answer is "!!". For "z" and n = 1 the string has one character, which is both first and last, so the answer is "z". The number n is between 1 and 10.
Approach
There are two jobs. First, find the last character. Second, build a string that holds n copies of it. The second job needs no loop, because the std::string class has a constructor that does exactly that.
Indexes start at 0, so a string of length 6 has indexes 0 to 5, and the last character is at index s.size() - 1. Indexing with [] gives a single char, which is what the constructor wants.
Step by step
- Get the last character.
s[s.size() - 1]is thecharat the last index. - Build the repeated string.
string(n, c)creates a string ofncopies of the characterc. The count comes first and the character second. - Return it. The whole function is one expression, so the constructor call is the returned value.
The solution in C++
class Solution {
public:
string repeatLastChar(string s, int n) {
return string(n, s[s.size() - 1]);
}
};
The details that matter in C++:
- The fill constructor.
string(3, 'x')is"xxx". It builds a new string directly, with no loop and no repeated+=. - Argument order. Swapping the arguments, as in
string('x', 3), still compiles, because acharconverts to a number and the number 3 converts to achar. It builds a string of 120 copies (the character code of'x') of the character with code 3, which is a control character, not a letter. Count first, then the character. charversus string.s[i]is achar, written with single quotes when it is a literal, like'r'. A string literal uses double quotes. The fill constructor needs achar.- An alternative.
s.back()returns the last character too, and it reads more clearly thans[s.size() - 1]. Both need a non-empty string. - Empty strings. Indexing an empty string at
size() - 1reads far outside the string, becausesize() - 1wraps around to a huge unsigned number. The lesson's strings always have at least one character.
Edge cases and common mistakes
- Using index
s.size(). The last valid index is one less than the length. Index 6 in"banana"is not a letter. - Taking the first character by mistake.
s[0]for"banana"is'b', which would give"bbb". - Adding characters. Repeating with
s[i] + s[i]adds two character codes as numbers instead of joining text. The fill constructor avoids that trap. - Using
nas the index.nis how many copies to write, and it has nothing to do with the position of the character. - A single-character string.
"z"withn = 1gives"z". The last index is 0, and the code works as it is.
Testing
"banana"and3give"aaa"."Wow!"and2give"!!"."z"and1give"z".
