-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path3884.py
More file actions
52 lines (39 loc) · 1.21 KB
/
3884.py
File metadata and controls
52 lines (39 loc) · 1.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
"""3884. First Matching Character From Both Ends
You are given a string s of length n consisting of lowercase English letters.
Return the smallest index i such that s[i] == s[n - i - 1].
If no such index exists, return -1.
Example 1:
Input: s = "abcacbd"
Output: 1
Explanation:
At index i = 1, s[1] and s[5] are both 'b'.
No smaller index satisfies the condition, so the answer is 1.
Example 2:
Input: s = "abc"
Output: 1
Explanation:
At index i = 1, the two compared positions coincide, so both characters are 'b'.
No smaller index satisfies the condition, so the answer is 1.
Example 3:
Input: s = "abcdab"
Output: -1
Explanation:
For every index i, the characters at positions i and n - i - 1 are different.
Therefore, no valid index exists, so the answer is -1."""
class Solution:
def firstMatchingIndex(self, s: str) -> int:
n = len(s)
for i in range(n):
if s[i] == s[n - i - 1]:
return i
return -1
# Test cases
if __name__ == "__main__":
sol = Solution()
test_cases = [
"abcacbd",
"abc",
"abcdab"
]
for s in test_cases:
print(f"{s} => {sol.firstMatchingIndex(s)}")