How to find the last repeated character in a string with Python

2 Answers

0 votes
def get_last_character_repeated(s): 
    ln = len(s)
    ch_idx = -1

    for i in range(ln): 
        for j in range (i + 1, ln): 
            if (s[i] == s[j]): 
                ch_idx = i;
                break

    return ch_idx 
 
   
s = "abcdxypcbadom"
i = get_last_character_repeated(s) 
if (i == -1): 
    print("Not found") 
else: 
    print (s[i]) 
 
 
 
'''
run:
 
d
 
'''

 



answered Jan 25, 2020 by avibootz
edited Nov 1 by avibootz
0 votes
from collections import Counter


def find_last_repeated_character(s: str) -> str | None:
    """
    Finds the last repeated character in a string.

    Examples:
        "abca"          -> "a"
        "abcbd"         -> "b"
        "abcde"         -> None
        "abcdxypcbop"   -> "p"
        "abcdxypcbadom" -> "d"

    Time Complexity: O(n)
    Space Complexity: O(k)

    Args:
        s: Input string.

    Returns:
        The last repeated character, or None if no repeated
        character exists.
    """
    # Count occurrences of each character.
    frequencies = Counter(s)

    # Scan from right to left.
    for ch in reversed(s):
        if frequencies[ch] > 1:
            return ch

    # No repeated character found.
    return None


# Test cases
print(find_last_repeated_character("abca"))          
print(find_last_repeated_character("abcbd"))         
print(find_last_repeated_character("abcde"))         
print(find_last_repeated_character("abcdxypcbop"))   
print(find_last_repeated_character("abcdxypcbadom")) 


'''
run:

a
b
None
p
d

'''

 



answered Nov 1 by avibootz
...