Sobes.tech
Middle+

Python ülesanne: leia esimese unikaalse tähemärgi indeks stringis (First Unique Character)

sobes.tech AI

Vastus AI-lt

Selleks, et leida esimese mitte-korduva tähe indeks stringis, võite kasutada sõnastikku iga tähe esinemiste arvu arvutamiseks ning seejärel läbida stringi, et leida esimene tähemärk, mille arv on 1.

Python näide:

def first_unique_char(s):
    count = {}
    for ch in s:
        count[ch] = count.get(ch, 0) + 1
    for i, ch in enumerate(s):
        if count[ch] == 1:
            return i
    return -1

# Kasutusnäide
s = "leetcode"
print(first_unique_char(s))  # Väljund 0

s = "loveleetcode"
print(first_unique_char(s))  # Väljund 2

s = "aabb"
print(first_unique_char(s))  # Kui unikaalseid tähti pole, väljund -1