Find the first non-repeated character in a string

前端 未结 21 1420
有刺的猬
有刺的猬 2020-12-06 03:53

I read of a job interview question to write some code for the following:

Write an efficient function to find the first nonrepeated character in a st

相关标签:
21条回答
  • 2020-12-06 04:21

    Question: 1st non-repeating character in a string

    Method 1: making a count array

    a = "GGGiniiiiGinaaaPrrrottiijayi"
    count = [0]*256
    for ch in a: count[ord(ch)] +=1
    for ch in a :
        if( count[ord(ch)] == 1 ):
            print(ch)
            break
    

    Method2: List comprehension

    # 1st  non repeating character
    pal = [x for x in a if a.count(x) == 1][0]
    print(pal)
    

    Method 3: dictionary

    d={}
    for ch in a: d[ch] = d.get(ch,0)+1
    aa = sorted(d.items(), key = lambda ch  :ch[1])[0][0]
    print(aa)
    
    0 讨论(0)
  • 2020-12-06 04:21

    In Java, 1)Create the Character count hashmap. For each character,if there is no value stored in the character,set it to 1. Else increment the value of the character by 1 .

    2)Then I Scanned the String for each character. Return character if the count in hashmap is 1 . If no character has count 1 ,then return null.

    package com.abc.ridhi;
    import java.util.HashMap;
    import java.util.Scanner;
    
    public class FirstNonRepeated {
    
        public static void main(String[] args) {
            System.out.println(" Please enter the input string :");
            Scanner in = new Scanner(System.in);
            String s = in.nextLine();
            char c = firstNonRepeatedCharacter(s);
            System.out.println("The first non repeated character is :  " + c);
        }
    
        public static Character firstNonRepeatedCharacter(String str) {
        HashMap<Character, Integer> map1 = new HashMap<Character, Integer>();
            int i, length;
            Character c;
            length = str.length(); 
            // Scan string and build hashmap
            for (i = 0; i < length; i++) {
                c = str.charAt(i);
                if (map1.containsKey(c)) {
                    // increment count corresponding to c
                    map1.put(c, map1.get(c) + 1);
                } else {
                    map1.put(c, 1);
                }
            }
            // Search map in order of string str
    
            for (i = 0; i < length; i++) {
                c = str.charAt(i);
                if (map1.get(c) == 1){
                    return c;
            }
            }
            return null;
        }
    }
    
    0 讨论(0)
  • 2020-12-06 04:21

    The following code traverses through the string only once. It's a simple and easy solution for the problem but at the same time the space complexity is compromised.

    def firstNonRepeating(a):
        inarr = []
        outarr = []
    
        for i in a:
            #print i
            if not i in inarr:
                inarr.append(i)
                outarr.append(i)
            elif i in outarr:
                outarr.remove(i)
            else:
                continue
        return outarr[0]
    
    a = firstNonRepeating(“Your String”)
    print a
    
    0 讨论(0)
  • 2020-12-06 04:24

    My solution. I can't speak to how efficient it is; I think it runs in n^2 time.

    >>> def fst_nr(s):
    ...     collection = []
    ...     for i in range(len(s)):
    ...             if not s[i] in collection and not s[i] in s[i+1:]:
    ...                     return s[i]
    ...             else:
    ...                     collection+=[s[i]]
    ... 
    >>> fst_nr("teeter")
    'r'
    >>> fst_nr("floccinaucinihilipilification")
    'u'
    >>> fst_nr("floccinacinihilipilification")
    'h'
    >>> fst_nr("floccinaciniilipilification")
    'p'
    >>> fst_nr("floccinaciniiliilification")
    't'
    >>> fst_nr("floccinaciniiliilificaion")
    >>> 
    

    Any advice for a humble Stack noob?

    0 讨论(0)
  • 2020-12-06 04:25

    Since we need the first non-repeating character, it is better to use OrderedDict from collections because dict does not guarantee the order of the keys

    from collections import OrderedDict
    dict_values = OrderedDict()
    string = "abcdcd"
    
    for char in string:
       if char in dict_values:
       dict_values[char] += 1
    else:
        dict_values[char] = 1
    
    for key,value in dict_values.items():
        if value == 1:
           print ("First non repeated character is %s"%key)
           break
        else:
           pass
    
    0 讨论(0)
  • 2020-12-06 04:26
    def firstnonrecur(word):
    
        for c in word:
            if word.count(c) == 1:
                print(c)
                break
    
    
    firstnonrecur('google')
    

    How about this?

    0 讨论(0)
提交回复
热议问题