Given a string s and a single character target, return the zero-based index of the last occurrence of target in s. If target does not appear in s, return -1.
The string s contains only ASCII letters ('a'-'z' and 'A'-'Z') and may be empty. target is exactly one ASCII letter. Matching is case-sensitive, so 'a' and 'A' are different characters.
You must not use built-in search methods that find the last occurrence for you (such as rfind, rindex, lastIndexOf, or equivalents). Traverse the string directly.
Function Signature
def last_index_of_character(s: str, target: str) -> int:
Rules
-
Indices are zero-based.
-
Return
-1
when
target
does not occur in
s
, including when
s
is empty.
-
Comparison is case-sensitive:
'B'
does not match
'b'
.
-
Library routines that search for the last occurrence (
rfind
,
rindex
,
lastIndexOf
and their equivalents) are not allowed.
Constraints
-
0 <= len(s) <= 10^5
-
s
consists only of ASCII letters
a
-
z
and
A
-
Z
.
-
len(target) == 1
-
target
is an ASCII letter
a
-
z
or
A
-
Z
.
Examples
Input: s = "programming", target = "g"
Output: 10
'g' appears at indices 3 and 10. The last occurrence is at index 10.
Input: s = "Banana", target = "b"
Output: -1
Matching is case-sensitive. The string has only an uppercase 'B', so lowercase 'b' is not found and the answer is -1.
Input: s = "", target = "a"
Output: -1
The empty string contains no characters, so there is no occurrence to report.