📌  相关文章
📜  给定一个字符串,找到它的第一个非重复字符

📅  最后修改于: 2022-05-13 01:57:07.020000             🧑  作者: Mango

给定一个字符串,找到它的第一个非重复字符

给定一个字符串,找出其中第一个不重复的字符。例如,如果输入字符串是“GeeksforGeeks”,那么输出应该是“f”,如果输入字符串是“GeeksQuiz”,那么输出应该是“G”。

在字符串中查找第一个非重复字符

例子:

Input: "geeksforgeeks"
Explanation:
Step 1: Construct a character count array 
        from the input string.
   ....
  count['e'] = 4
  count['f'] = 1
  count['g'] = 2
  count['k'] = 2
  ……

Step 2: Get the first character who's 
        count is 1 ('f').

方法一 HashMap 和双字符串方法遍历。
方法:如果一个字符在字符串中的频率为单位,则称该字符为非重复字符。现在要找到这样的字符,需要找到字符串中所有字符的频率,并检查哪个字符具有单位频率。这个任务可以使用hash_map有效地完成,它将字符映射到相应的频率,并且我们可以同时更新我们在恒定时间内遇到的任何字符的频率。 ASCII 系统中的最大不同字符是 256 。所以hash_map的最大大小为256 。现在再次读取字符串,我们找到的第一个字符有一个频率,因为统一就是答案。
算法:

  1. 制作一个hash_map将字符映射到相应的频率。
  2. 使用指针遍历给定的字符串。
  3. 增加hash_map中当前字符的计数。
  4. 现在再次遍历字符串并检查当前字符是否有frequency=1
  5. 如果频率>1继续遍历。
  6. 否则打破循环并打印当前字符作为答案。

伪代码:

for ( i=0 to str.length())
hash_map[str[i]]++;

for(i=0 to str.length())
  if(hash_map[str[i]]==1)
  return str[i]
C++
// C++ program to find first
// non-repeating character
#include 
using namespace std;
#define NO_OF_CHARS 256
 
/* Returns an array of size 256 containing count
of characters in the passed char array */
int* getCharCountArray(char* str)
{
    int* count = (int*)calloc(sizeof(int), NO_OF_CHARS);
    int i;
    for (i = 0; *(str + i); i++)
        count[*(str + i)]++;
    return count;
}
 
/* The function returns index of first
non-repeating character in a string. If all
characters are repeating then returns -1 */
int firstNonRepeating(char* str)
{
    int* count = getCharCountArray(str);
    int index = -1, i;
 
    for (i = 0; *(str + i); i++) {
        if (count[*(str + i)] == 1) {
            index = i;
            break;
        }
    }
 
    // To avoid memory leak
    free(count);
    return index;
}
 
/* Driver program to test above function */
int main()
{
    char str[] = "geeksforgeeks";
    int index = firstNonRepeating(str);
    if (index == -1)
        cout << "Either all characters are repeating or "
            "string is empty";
    else
        cout << "First non-repeating character is "<<
            str[index];
    getchar();
    return 0;
}
 
// This code is contributed by shivanisinghss2110


C
// C program to find first
// non-repeating character
#include 
#include 
#define NO_OF_CHARS 256
 
/* Returns an array of size 256 containing count
   of characters in the passed char array */
int* getCharCountArray(char* str)
{
    int* count = (int*)calloc(sizeof(int), NO_OF_CHARS);
    int i;
    for (i = 0; *(str + i); i++)
        count[*(str + i)]++;
    return count;
}
 
/* The function returns index of first
   non-repeating character in a string. If all
   characters are repeating then returns -1 */
int firstNonRepeating(char* str)
{
    int* count = getCharCountArray(str);
    int index = -1, i;
 
    for (i = 0; *(str + i); i++) {
        if (count[*(str + i)] == 1) {
            index = i;
            break;
        }
    }
 
    // To avoid memory leak
    free(count);
    return index;
}
 
/* Driver program to test above function */
int main()
{
    char str[] = "geeksforgeeks";
    int index = firstNonRepeating(str);
    if (index == -1)
        printf("Either all characters are repeating or "
               "string is empty");
    else
        printf("First non-repeating character is %c",
               str[index]);
    getchar();
    return 0;
}


Java
// Java program to find first
// non-repeating character
class GFG {
    static final int NO_OF_CHARS = 256;
    static char count[] = new char[NO_OF_CHARS];
 
    /* calculate count of characters
       in the passed string */
    static void getCharCountArray(String str)
    {
        for (int i = 0; i < str.length(); i++)
            count[str.charAt(i)]++;
    }
 
    /* The method returns index of first non-repeating
       character in a string. If all characters are repeating
       then returns -1 */
    static int firstNonRepeating(String str)
    {
        getCharCountArray(str);
        int index = -1, i;
 
        for (i = 0; i < str.length(); i++) {
            if (count[str.charAt(i)] == 1) {
                index = i;
                break;
            }
        }
 
        return index;
    }
 
    // Driver method
    public static void main(String[] args)
    {
        String str = "geeksforgeeks";
        int index = firstNonRepeating(str);
 
        System.out.println(
            index == -1
                ? "Either all characters are repeating or string "
                      + "is empty"
                : "First non-repeating character is "
                      + str.charAt(index));
    }
}


Python3
# Python program to print the first non-repeating character
NO_OF_CHARS = 256
 
# Returns an array of size 256 containing count
# of characters in the passed char array
def getCharCountArray(string):
    count = [0] * NO_OF_CHARS
    for i in string:
        count[ord(i)]+= 1
    return count
 
# The function returns index of first non-repeating
# character in a string. If all characters are repeating
# then returns -1
def firstNonRepeating(string):
    count = getCharCountArray(string)
    index = -1
    k = 0
 
    for i in string:
        if count[ord(i)] == 1:
            index = k
            break
        k += 1
 
    return index
 
# Driver program to test above function
string = "geeksforgeeks"
index = firstNonRepeating(string)
if index == 1:
    print ("Either all characters are repeating or string is empty")
else:
    print ("First non-repeating character is" , string[index])
 
# This code is contributed by Bhavya Jain


C#
// C# program to find first non-repeating character
using System;
using System.Globalization;
 
class GFG {
 
    static int NO_OF_CHARS = 256;
    static char[] count = new char[NO_OF_CHARS];
 
    /* calculate count of characters
    in the passed string */
    static void getCharCountArray(string str)
    {
        for (int i = 0; i < str.Length; i++)
            count[str[i]]++;
    }
 
    /* The method returns index of first non-repeating
    character in a string. If all characters are
    repeating then returns -1 */
    static int firstNonRepeating(string str)
    {
        getCharCountArray(str);
        int index = -1, i;
 
        for (i = 0; i < str.Length; i++) {
            if (count[str[i]] == 1) {
                index = i;
                break;
            }
        }
 
        return index;
    }
 
    // Driver code
    public static void Main()
    {
        string str = "geeksforgeeks";
        int index = firstNonRepeating(str);
 
        Console.WriteLine(index == -1 ? "Either "
                                            + "all characters are repeating or string "
                                            + "is empty"
                                      : "First non-repeating character"
                                            + " is " + str[index]);
    }
}
 
// This code is contributed by Sam007


PHP


C++
// CPP program to find first non-repeating
// character
#include 
using namespace std;
#define NO_OF_CHARS 256
 
/* The function returns index of the first
   non-repeating character in a string. If
   all characters are repeating then
   returns INT_MAX */
int firstNonRepeating(char* str)
{
    pair arr[NO_OF_CHARS];
 
    for (int i = 0; str[i]; i++) {
        (arr[str[i]].first)++;
        arr[str[i]].second = i;
    }
 
    int res = INT_MAX;
    for (int i = 0; i < NO_OF_CHARS; i++)
 
        // If this character occurs only
        // once and appears before the
        // current result, then update the
        // result
        if (arr[i].first == 1)
            res = min(res, arr[i].second);
 
    return res;
}
 
/* Driver program to test above function */
int main()
{
    char str[] = "geeksforgeeks";
    int index = firstNonRepeating(str);
    if (index == INT_MAX)
        printf("Either all characters are "
               "repeating or string is empty");
    else
        printf("First non-repeating character"
               " is %c",
               str[index]);
    return 0;
}


C
#include 
#include 
#include 
#define NO_OF_CHARS 256
 
// Structure to store count of a
// character and index of the first
// occurrence in the input string
struct countIndex {
    int count;
    int index;
};
 
/* Returns an array of above
structure type. The size of
array is NO_OF_CHARS */
struct countIndex* getCharCountArray(char* str)
{
    struct countIndex* count = (struct countIndex*)calloc(
        sizeof(struct countIndex), NO_OF_CHARS);
    int i;
    for (i = 0; *(str + i); i++) {
        (count[*(str + i)].count)++;
 
        // If it's first occurrence,
        // then store the index
        if (count[*(str + i)].count == 1)
            count[*(str + i)].index = i;
    }
    return count;
}
 
/* The function returns index of the
    first non-repeating character in
    a string. If all characters are
    repeating then returns INT_MAX */
int firstNonRepeating(char* str)
{
    struct countIndex* count
        = getCharCountArray(str);
    int result = INT_MAX, i;
 
    for (i = 0; i < NO_OF_CHARS; i++) {
        // If this character occurs
        // only once and appears
        // before the current result,
        // then update the result
        if (count[i].count == 1
            && result > count[i].index)
            result = count[i].index;
    }
 
    // To avoid memory leak
    free(count);
    return result;
}
 
/* Driver program to test above function */
int main()
{
    char str[] = "geeksforgeeks";
    int index = firstNonRepeating(str);
    if (index == INT_MAX)
        printf("Either all characters are"
               " repeating or string is empty");
    else
        printf("First non-repeating character"
               " is %c",
               str[index]);
    getchar();
    return 0;
}


Java
// Java program to find first
// non-repeating character
// Note : hashmap is used
 
import java.util.*;
 
class CountIndex {
    int count, index;
 
    // constructor for first occurrence
    public CountIndex(int index)
    {
        this.count = 1;
        this.index = index;
    }
 
    // method for updating count
    public void incCount()
    {
        this.count++;
    }
}
class GFG {
    static final int NO_OF_CHARS = 256;
 
    static HashMap hm
        = new HashMap(NO_OF_CHARS);
 
    /* calculate count of characters
       in the passed string */
    static void getCharCountArray(String str)
    {
        for (int i = 0; i < str.length(); i++) {
            // If character already occurred,
            if (hm.containsKey(str.charAt(i))) {
                // updating count
                hm.get(str.charAt(i)).incCount();
            }
 
            // If it's first occurrence, then store
            // the index and count = 1
            else {
                hm.put(str.charAt(i), new CountIndex(i));
            }
        }
    }
 
    /* The method returns index of first non-repeating
       character in a string. If all characters are repeating
       then returns -1 */
    static int firstNonRepeating(String str)
    {
        getCharCountArray(str);
        int result = Integer.MAX_VALUE, i;
        for (Map.Entry entry : hm.entrySet())
        {
            int c=entry.getValue().count;
            int ind=entry.getValue().index;
            if(c==1 && ind < result)
            {
                result=ind;
            }
        }
       
 
        return result;
    }
 
    // Driver method
    public static void main(String[] args)
    {
        String str = "geeksforgeeks";
        int index = firstNonRepeating(str);
 
        System.out.println(
            index == Integer.MAX_VALUE
                ? "Either all characters are repeating "
                      + " or string is empty"
                : "First non-repeating character is "
                      + str.charAt(index));
    }
}


C#
// C# program to find first
// non-repeating character
// Note : hashmap is used
using System;
using System.Collections.Generic;
 
class CountIndex {
    public int count, index;
 
    // constructor for first occurrence
    public CountIndex(int index)
    {
        this.count = 1;
        this.index = index;
    }
 
    // method for updating count
    public virtual void incCount()
    {
        this.count++;
    }
}
 
class GFG {
    public const int NO_OF_CHARS = 256;
 
    public static Dictionary
        hm = new Dictionary(NO_OF_CHARS);
 
    /* calculate count of characters
    in the passed string */
    public static void getCharCountArray(string str)
    {
        for (int i = 0; i < str.Length; i++) {
            // If character already occurred,
            if (hm.ContainsKey(str[i])) {
                // updating count
                hm[str[i]].incCount();
            }
 
            // If it's first occurrence, then
            // store the index and count = 1
            else {
                hm[str[i]] = new CountIndex(i);
            }
        }
    }
 
    /* The method returns index of first
    non-repeating character in a string.
    If all characters are repeating then
    returns -1 */
    internal static int firstNonRepeating(string str)
    {
        getCharCountArray(str);
        int result = int.MaxValue, i;
 
        for (i = 0; i < str.Length; i++) {
            // If this character occurs only
            // once and appears before the
            // current result, then update the result
            if (hm[str[i]].count == 1 && result > hm[str[i]].index) {
                result = hm[str[i]].index;
            }
        }
 
        return result;
    }
 
    // Driver Code
    public static void Main(string[] args)
    {
        string str = "geeksforgeeks";
        int index = firstNonRepeating(str);
 
        Console.WriteLine(
            index == int.MaxValue
                ? "Either all characters are repeating "
                      + " or string is empty"
                : "First non-repeating character is "
                      + str[index]);
    }
}
 
// This code is contributed by Shrikant13


Javascript


C++
// CPP program to find first non-repeating
// character
# include
# include
 
using namespace std;
 
// this function return the index of first non-repeating
// character if found, or else it returns -1
int firstNonRepeating(string str) {
    int fi[256]; // array to store First Index
 
    // initializing all elements to -1
    for(int i = 0; i<256; i++)
        fi[i] = -1;
 
    // sets all repeating characters to -2 and non-repeating characters
      // contain the index where they occur
    for(int i = 0; i= 0)
            res = min(res, fi[i]);
    }
     
    // if res remains INT_MAX, it means there are no
    // characters that repeat only once or the string is empty
    if(res == INT_MAX) return -1;
    else return res;
}
 
int main(){
    string str;
      str = "geeksforgeeks";
    int firstIndex = firstNonRepeating(str);
    if (firstIndex == -1)
        cout<<"Either all characters are repeating or string is empty";
    else
        cout<<"First non-repeating character is "<< str[firstIndex];
     
    return 0;
}


Java
// JAVA program to find first non-repeating
// character
public class GFG {
     
// this function return the index of first non-repeating
// character if found, or else it returns -1
public static int firstNonRepeating(String str) {
    int[] fi = new int [256]; // array to store First Index
 
    // initializing all elements to -1
    for(int i = 0; i<256; i++)
        fi[i] = -1;
 
    // sets all repeating characters to -2 and non-repeating characters
      // contain the index where they occur
    for(int i = 0; i= 0)
            res = Math.min(res, fi[i]);
    }
     
    // if res remains  Integer.MAX_VALUE, it means there are no
    // characters that repeat only once or the string is empty
    if(res ==  Integer.MAX_VALUE) return -1;
    else return res;
}
 
public static void main(String args[]){
    String str;
    str = "geeksforgeeks";
    int firstIndex = firstNonRepeating(str);
    if (firstIndex == -1)
       System.out.println("Either all characters are repeating or string is empty");
    else
       System.out.println("First non-repeating character is "+ str.charAt(firstIndex));
    }
}
//This code is contributed by SoumikMondal


C#
// C# program to find first non-repeating
// character
using System;
public class GFG {
 
    // this function return the index of first non-repeating
    // character if found, or else it returns -1
    public static int firstNonRepeating(string str)
    {
        int[] fi
            = new int[256]; // array to store First Index
 
        // initializing all elements to -1
        for (int i = 0; i < 256; i++)
            fi[i] = -1;
 
        // sets all repeating characters to -2 and
        // non-repeating characters contain the index where
        // they occur
        for (int i = 0; i < str.Length; i++) {
            if (fi[str[i]] == -1) {
                fi[str[i]] = i;
            }
            else {
                fi[str[i]] = -2;
            }
        }
 
        int res = Int32.MaxValue;
 
        for (int i = 0; i < 256; i++) {
 
            // If this character is not -1 or -2 then it
            // means that this character occurred only once
            // so find the min index of all characters that
            // occur only once, that's our first index
            if (fi[i] >= 0)
                res = Math.Min(res, fi[i]);
        }
 
        // if res remains  Integer.MAX_VALUE, it means there
        // are no characters that repeat only once or the
        // string is empty
        if (res == Int32.MaxValue)
            return -1;
        else
            return res;
    }
 
    public static void Main()
    {
        string str;
        str = "geeksforgeeks";
        int firstIndex = firstNonRepeating(str);
        if (firstIndex == -1)
            Console.WriteLine(
                "Either all characters are repeating or string is empty");
        else
            Console.WriteLine(
                "First non-repeating character is "
                + str[firstIndex]);
    }
}
 
// This code is contributed by ukasp.


Javascript


Python3
# Python implementation
from collections import Counter
 
# Function which repeats
# first Nonrepeating character
def printNonrepeated(string):
 
    # Calculating frequencies
    # using Counter function
    freq = Counter(string)
 
    # Traverse the string
    for i in string:
        if(freq[i] == 1):
            print(i)
            break
 
 
# Driver code
string = "geeksforgeeks"
 
# passing string to printNonrepeated function
printNonrepeated(string)
 
# this code is contributed by vikkycirus


Python3
# python3 implementation
 
def FirstNonRepeat(s):
 
   for i in s:
 
       if (s.find(i,(s.find(i)+1))) == -1:
 
           print(i)
 
           break
 
   return
 
#__main__
 
s = 'geeksforgeeks'
 
FirstNonRepeat(s)


Javascript


输出
First non-repeating character is f

这可以通过只遍历字符串一次来完成吗?
上述方法需要O(n)时间,但在实践中,它可以改进。算法的第一部分遍历字符串以构造计数数组(在O(n)时间内)。这是合理的。但是第二部分关于再次遍历字符串只是为了找到第一个不重复的不是一个好习惯。
在实际情况下,字符串应该比您的字母表大得多。以 DNA 序列为例,它们可能有数百万个字母,而字母表只有 4 个字母。如果 non-repeater 在字符串的末尾会发生什么?然后我们将不得不扫描很长时间(再次)。
方法二 HashMap和单字符串遍历。
方法:制作一个计数数组而不是最大字符数(256)的 hash_map。我们不仅可以存储计数,还可以存储您第一次遇到字符的索引来增加计数数组,例如 (3, 26) 表示“a”,这意味着“a”被计算了 3 次,第一次被看到是在第 26 位。因此,在查找第一个非重复节点时,我们只需要扫描 count 数组,而不是字符串。感谢 Ben 提出这种方法。
算法 :

  1. 制作一个count_array ,它将有两个字段,即频率,第一次出现一个字符
  2. count_array的大小是'256'
  3. 使用指针遍历给定的字符串。
  4. 增加当前字符的计数并更新出现次数。
  5. 现在有一个问题,数组将包含有效的第一次出现频率一致的字符,否则第一次出现会不断更新。
  6. 现在遍历 count_array 并找到第一次出现的最小值和频率值为单位的字符。
  7. 返回字符

伪代码:

for ( i=0 to str.length())
count_arr[str[i]].first++;
count_arr[str[i]].second=i;

int res=INT_MAX;
for(i=0 to count_arr.size())
  if(count_arr[str[i]].first==1)
  res=min(min, count_arr[str[i]].second)

return res

C++

// CPP program to find first non-repeating
// character
#include 
using namespace std;
#define NO_OF_CHARS 256
 
/* The function returns index of the first
   non-repeating character in a string. If
   all characters are repeating then
   returns INT_MAX */
int firstNonRepeating(char* str)
{
    pair arr[NO_OF_CHARS];
 
    for (int i = 0; str[i]; i++) {
        (arr[str[i]].first)++;
        arr[str[i]].second = i;
    }
 
    int res = INT_MAX;
    for (int i = 0; i < NO_OF_CHARS; i++)
 
        // If this character occurs only
        // once and appears before the
        // current result, then update the
        // result
        if (arr[i].first == 1)
            res = min(res, arr[i].second);
 
    return res;
}
 
/* Driver program to test above function */
int main()
{
    char str[] = "geeksforgeeks";
    int index = firstNonRepeating(str);
    if (index == INT_MAX)
        printf("Either all characters are "
               "repeating or string is empty");
    else
        printf("First non-repeating character"
               " is %c",
               str[index]);
    return 0;
}

C

#include 
#include 
#include 
#define NO_OF_CHARS 256
 
// Structure to store count of a
// character and index of the first
// occurrence in the input string
struct countIndex {
    int count;
    int index;
};
 
/* Returns an array of above
structure type. The size of
array is NO_OF_CHARS */
struct countIndex* getCharCountArray(char* str)
{
    struct countIndex* count = (struct countIndex*)calloc(
        sizeof(struct countIndex), NO_OF_CHARS);
    int i;
    for (i = 0; *(str + i); i++) {
        (count[*(str + i)].count)++;
 
        // If it's first occurrence,
        // then store the index
        if (count[*(str + i)].count == 1)
            count[*(str + i)].index = i;
    }
    return count;
}
 
/* The function returns index of the
    first non-repeating character in
    a string. If all characters are
    repeating then returns INT_MAX */
int firstNonRepeating(char* str)
{
    struct countIndex* count
        = getCharCountArray(str);
    int result = INT_MAX, i;
 
    for (i = 0; i < NO_OF_CHARS; i++) {
        // If this character occurs
        // only once and appears
        // before the current result,
        // then update the result
        if (count[i].count == 1
            && result > count[i].index)
            result = count[i].index;
    }
 
    // To avoid memory leak
    free(count);
    return result;
}
 
/* Driver program to test above function */
int main()
{
    char str[] = "geeksforgeeks";
    int index = firstNonRepeating(str);
    if (index == INT_MAX)
        printf("Either all characters are"
               " repeating or string is empty");
    else
        printf("First non-repeating character"
               " is %c",
               str[index]);
    getchar();
    return 0;
}

Java

// Java program to find first
// non-repeating character
// Note : hashmap is used
 
import java.util.*;
 
class CountIndex {
    int count, index;
 
    // constructor for first occurrence
    public CountIndex(int index)
    {
        this.count = 1;
        this.index = index;
    }
 
    // method for updating count
    public void incCount()
    {
        this.count++;
    }
}
class GFG {
    static final int NO_OF_CHARS = 256;
 
    static HashMap hm
        = new HashMap(NO_OF_CHARS);
 
    /* calculate count of characters
       in the passed string */
    static void getCharCountArray(String str)
    {
        for (int i = 0; i < str.length(); i++) {
            // If character already occurred,
            if (hm.containsKey(str.charAt(i))) {
                // updating count
                hm.get(str.charAt(i)).incCount();
            }
 
            // If it's first occurrence, then store
            // the index and count = 1
            else {
                hm.put(str.charAt(i), new CountIndex(i));
            }
        }
    }
 
    /* The method returns index of first non-repeating
       character in a string. If all characters are repeating
       then returns -1 */
    static int firstNonRepeating(String str)
    {
        getCharCountArray(str);
        int result = Integer.MAX_VALUE, i;
        for (Map.Entry entry : hm.entrySet())
        {
            int c=entry.getValue().count;
            int ind=entry.getValue().index;
            if(c==1 && ind < result)
            {
                result=ind;
            }
        }
       
 
        return result;
    }
 
    // Driver method
    public static void main(String[] args)
    {
        String str = "geeksforgeeks";
        int index = firstNonRepeating(str);
 
        System.out.println(
            index == Integer.MAX_VALUE
                ? "Either all characters are repeating "
                      + " or string is empty"
                : "First non-repeating character is "
                      + str.charAt(index));
    }
}

C#

// C# program to find first
// non-repeating character
// Note : hashmap is used
using System;
using System.Collections.Generic;
 
class CountIndex {
    public int count, index;
 
    // constructor for first occurrence
    public CountIndex(int index)
    {
        this.count = 1;
        this.index = index;
    }
 
    // method for updating count
    public virtual void incCount()
    {
        this.count++;
    }
}
 
class GFG {
    public const int NO_OF_CHARS = 256;
 
    public static Dictionary
        hm = new Dictionary(NO_OF_CHARS);
 
    /* calculate count of characters
    in the passed string */
    public static void getCharCountArray(string str)
    {
        for (int i = 0; i < str.Length; i++) {
            // If character already occurred,
            if (hm.ContainsKey(str[i])) {
                // updating count
                hm[str[i]].incCount();
            }
 
            // If it's first occurrence, then
            // store the index and count = 1
            else {
                hm[str[i]] = new CountIndex(i);
            }
        }
    }
 
    /* The method returns index of first
    non-repeating character in a string.
    If all characters are repeating then
    returns -1 */
    internal static int firstNonRepeating(string str)
    {
        getCharCountArray(str);
        int result = int.MaxValue, i;
 
        for (i = 0; i < str.Length; i++) {
            // If this character occurs only
            // once and appears before the
            // current result, then update the result
            if (hm[str[i]].count == 1 && result > hm[str[i]].index) {
                result = hm[str[i]].index;
            }
        }
 
        return result;
    }
 
    // Driver Code
    public static void Main(string[] args)
    {
        string str = "geeksforgeeks";
        int index = firstNonRepeating(str);
 
        Console.WriteLine(
            index == int.MaxValue
                ? "Either all characters are repeating "
                      + " or string is empty"
                : "First non-repeating character is "
                      + str[index]);
    }
}
 
// This code is contributed by Shrikant13

Javascript


输出
First non-repeating character is f

复杂性分析:

  • 时间复杂度: O(n)。
    因为字符串至少需要遍历一次。
  • 辅助空间: O(n)。
    空间被使用count_array/hash_map来跟踪频率。

方法#3:计数数组和单字符串遍历:

方法:

创建一个最大字符数(256)的计数数组。我们可以将这个数组中的所有元素初始化为-1。然后逐个字符地循环遍历我们的字符串并检查字符字符索引的数组元素是否为-1。如果是-1,则将其更改为i,如果不是-1,则表示该字符之前已出现,因此将其更改为-2。

最后,所有重复字符都将更改为 -2,所有非重复字符将包含它们出现的索引。现在我们可以遍历所有不重复的字符并找到最小索引或第一个索引。

C++

// CPP program to find first non-repeating
// character
# include
# include
 
using namespace std;
 
// this function return the index of first non-repeating
// character if found, or else it returns -1
int firstNonRepeating(string str) {
    int fi[256]; // array to store First Index
 
    // initializing all elements to -1
    for(int i = 0; i<256; i++)
        fi[i] = -1;
 
    // sets all repeating characters to -2 and non-repeating characters
      // contain the index where they occur
    for(int i = 0; i= 0)
            res = min(res, fi[i]);
    }
     
    // if res remains INT_MAX, it means there are no
    // characters that repeat only once or the string is empty
    if(res == INT_MAX) return -1;
    else return res;
}
 
int main(){
    string str;
      str = "geeksforgeeks";
    int firstIndex = firstNonRepeating(str);
    if (firstIndex == -1)
        cout<<"Either all characters are repeating or string is empty";
    else
        cout<<"First non-repeating character is "<< str[firstIndex];
     
    return 0;
}

Java

// JAVA program to find first non-repeating
// character
public class GFG {
     
// this function return the index of first non-repeating
// character if found, or else it returns -1
public static int firstNonRepeating(String str) {
    int[] fi = new int [256]; // array to store First Index
 
    // initializing all elements to -1
    for(int i = 0; i<256; i++)
        fi[i] = -1;
 
    // sets all repeating characters to -2 and non-repeating characters
      // contain the index where they occur
    for(int i = 0; i= 0)
            res = Math.min(res, fi[i]);
    }
     
    // if res remains  Integer.MAX_VALUE, it means there are no
    // characters that repeat only once or the string is empty
    if(res ==  Integer.MAX_VALUE) return -1;
    else return res;
}
 
public static void main(String args[]){
    String str;
    str = "geeksforgeeks";
    int firstIndex = firstNonRepeating(str);
    if (firstIndex == -1)
       System.out.println("Either all characters are repeating or string is empty");
    else
       System.out.println("First non-repeating character is "+ str.charAt(firstIndex));
    }
}
//This code is contributed by SoumikMondal

C#

// C# program to find first non-repeating
// character
using System;
public class GFG {
 
    // this function return the index of first non-repeating
    // character if found, or else it returns -1
    public static int firstNonRepeating(string str)
    {
        int[] fi
            = new int[256]; // array to store First Index
 
        // initializing all elements to -1
        for (int i = 0; i < 256; i++)
            fi[i] = -1;
 
        // sets all repeating characters to -2 and
        // non-repeating characters contain the index where
        // they occur
        for (int i = 0; i < str.Length; i++) {
            if (fi[str[i]] == -1) {
                fi[str[i]] = i;
            }
            else {
                fi[str[i]] = -2;
            }
        }
 
        int res = Int32.MaxValue;
 
        for (int i = 0; i < 256; i++) {
 
            // If this character is not -1 or -2 then it
            // means that this character occurred only once
            // so find the min index of all characters that
            // occur only once, that's our first index
            if (fi[i] >= 0)
                res = Math.Min(res, fi[i]);
        }
 
        // if res remains  Integer.MAX_VALUE, it means there
        // are no characters that repeat only once or the
        // string is empty
        if (res == Int32.MaxValue)
            return -1;
        else
            return res;
    }
 
    public static void Main()
    {
        string str;
        str = "geeksforgeeks";
        int firstIndex = firstNonRepeating(str);
        if (firstIndex == -1)
            Console.WriteLine(
                "Either all characters are repeating or string is empty");
        else
            Console.WriteLine(
                "First non-repeating character is "
                + str[firstIndex]);
    }
}
 
// This code is contributed by ukasp.

Javascript


输出

First non-repeating character is f

复杂性分析:

  • 时间复杂度:O(n)。

因为字符串需要遍历一次

  • 辅助空间: O(n)。

空间被使用计数阵列来跟踪频率所占用。

方法 #4:使用内置Python函数:

方法:

  1. 使用 Counter()函数计算所有字符的所有频率。
  2. 遍历字符串并检查是否有任何元素的频率为 1。
  3. 打印字符并中断循环。

下面是实现:

Python3

# Python implementation
from collections import Counter
 
# Function which repeats
# first Nonrepeating character
def printNonrepeated(string):
 
    # Calculating frequencies
    # using Counter function
    freq = Counter(string)
 
    # Traverse the string
    for i in string:
        if(freq[i] == 1):
            print(i)
            break
 
 
# Driver code
string = "geeksforgeeks"
 
# passing string to printNonrepeated function
printNonrepeated(string)
 
# this code is contributed by vikkycirus
输出
f

时间复杂度: O(n)。因为字符串至少需要遍历一次。

辅助空间: O(n)。

使用字符串函数find():

方法:

在当前位置之后搜索每个字母。如果它返回 -1,则意味着该字母仅出现一次,即当前索引。

执行:

Python3

# python3 implementation
 
def FirstNonRepeat(s):
 
   for i in s:
 
       if (s.find(i,(s.find(i)+1))) == -1:
 
           print(i)
 
           break
 
   return
 
#__main__
 
s = 'geeksforgeeks'
 
FirstNonRepeat(s)

Javascript


时间复杂度: O(n^2)

辅助空间: O(1)。