All Indices of Substring
Python
Medium
2 views
Problem Description
Read two strings s and p. Output all starting indices (0-based) where p occurs in s. If none, output -1.
Input Format
Two lines: s then p.
Output Format
Indices in one line space-separated or -1.
Official Solution
import sys
lines=sys.stdin.read().splitlines()
if len(lines)<2: sys.exit(0)
s=lines[0]
p=lines[1]
if p=='':
sys.stdout.write('0')
else:
out=[]
start=0
while True:
i=s.find(p,start)
if i==-1:
break
out.append(str(i))
start=i+1
sys.stdout.write(' '.join(out) if out else '-1')
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!