#C13191. Case-Insensitive Substring Search
Case-Insensitive Substring Search
Case-Insensitive Substring Search
Given two strings, haystack
and needle
, your task is to find the first occurrence of needle
in haystack
while ignoring case differences. The search should be case-insensitive, meaning that uppercase and lowercase letters are treated the same. If needle
is found, output its starting index (0-indexed). If needle
is not found, output -1
.
Note: If needle
is an empty string, output 0
.
The problem can be expressed in mathematical form as follows: \[ ans = \begin{cases} 0 & \text{if } needle = "" \\ \min \{ i : \text{lower}(haystack)[i:i+|needle|] = \text{lower}(needle) \} & \text{if such an } i \text{ exists} \\ -1 & \text{otherwise} \end{cases} \]
inputFormat
The input consists of two lines:
- The first line is the string
haystack
. - The second line is the string
needle
.
outputFormat
Output a single integer representing the starting index (0-indexed) of the first occurrence of needle
in haystack
(ignoring case), or -1
if needle
does not appear in haystack
. If needle
is empty, output 0
.
Hello, World!
world
7
</p>