Gets the first character and its position in a string that appears only once

Source: Internet
Author: User

Analysis:

First we need to count the number of occurrences of all characters and their position, and then the position of the characters that appear to be 1, the smallest

Suppose the string is:

' STRINGISASTARINGB '
Solution One:
def first_not_repeating_char (string):
    if not string:
        return-1
    resultdict = {}
    to K, s in enumerate (  String):
        resultdict [s] = [resultdict [s][0] + 1,k] if resultdict. Get (s) else [1,k]
    pos = Len (string)
    ret = None for
    x in resultdict:
        if Resultdict [x][0] ==1 and Resultdict [x][1] <pos:
            pos = resultdict [x][1]
            ret = (x,pos) return
    RET

The data structures involved include the following examples:

Statistical results: {' A ': [2, 9], ' B ': [1,], ' g ': [2,], ' I ': [3], ' n ': [2], ' s ': [3, ten], ' R ': [2, S], ' t ': [2, one]}

Return result: (' B ', 16)
Solution Two:
The use of two dictionaries a number, a storage location;
def first_not_repeating_char (string):
    if not string:
        return-1
    count = {}
    loc = {}
    for K, s in Enumera Te (string):
        count[s] = Count[s] + 1 if count.get (s) Else 1
        loc[s] = Loc[s] If Loc.get (s) Else k
    pos = Len (stri NG)
    ret = None for
    k in Loc.keys ():
        if Count.get (k) = = 1 and Loc[k] < pos:
            pos = loc[k]
            ret = (k , Loc[k]) return
    RET

The data structures involved include the following examples:

Count {' A ': 2, ' B ': 1, ' G ': 2, ' I ': 3, ' n ': 2, ' s ': 3, ' R ': 2, ' t ': 2}

loc {' A ': 8, ' B ': +, ' G ': 5, ' I ': 3, ' n ': 4, ' ' s ': 7, ' R ': 2, ' t ': 1}

(' B ', 16)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.