📌  相关文章
📜  按顺序打印字符串的所有不同字符(3 种方法)

📅  最后修改于: 2021-09-17 07:14:39             🧑  作者: Mango

给定一个字符串,找出其中所有不同的(或不重复的字符)。例如,如果输入字符串是“Geeks for Geeks”,那么输出应该是“for”,如果输入字符串是“Geeks Quiz”,那么输出应该是“GksQuiz”。
不同的字符应该按照它们在输入字符串出现的相同顺序打印。
例子:

Input  : Geeks for Geeks
Output : for

Input  : Hello Geeks
Output : HoGks

方法一(简单:O(n 2 ))
一个简单的解决方案是运行两个循环。从左侧开始遍历。对于每个字符,检查它是否重复。如果字符不重复,则增加非重复字符的计数。当计数变为 1 时,返回每个字符。
方法二(高效但需要两次遍历:O(n))

  1. 创建一个数组 count[] 来存储字符。
  2. 遍历输入字符串str 并对每个字符x = str[i] 执行以下操作。
    增量计数[x]。
  3. 再次遍历输入字符串并对每个字符str[i] 执行以下操作
    1. 如果 count[x] 为 1,则打印唯一字符
    2. 如果 count[x] 大于 1,则忽略重复的字符。

下面是上述想法的实现。

C++
// C++ program to print distinct characters of a
// string.
# include 
using namespace std;
# define NO_OF_CHARS 256
 
/* Print duplicates present in the passed string */
void printDistinct(char *str)
{
    // Create an array of size 256 and count of
    // every character in it
    int count[NO_OF_CHARS];
 
    /* Count array with frequency of characters */
    int i;
    for (i = 0; *(str+i); i++)
        if(*(str+i)!=' ')
            count[*(str+i)]++;
    int n = i;
 
    // Print characters having count more than 0
    for (i = 0; i < n; i++)
        if (count[*(str+i)] == 1)
            cout<< str[i];
}
 
/* Driver program*/
int main()
{
    char str[] = "GeeksforGeeks";
    printDistinct(str);
    return 0;
}


Java
// Java program to print distinct characters of a
// string.
public class GFG {
    static final int NO_OF_CHARS = 256;
      
    /* Print duplicates present in the passed string */
    static void printDistinct(String str)
    {
        // Create an array of size 256 and count of
        // every character in it
        int[] count = new int[NO_OF_CHARS];
      
        /* Count array with frequency of characters */
        int i;
        for (i = 0; i < str.length(); i++)
            if(str.charAt(i)!=' ')
                count[(int)str.charAt(i)]++;
        int n = i;
      
        // Print characters having count more than 0
        for (i = 0; i < n; i++)
            if (count[(int)str.charAt(i)] == 1)
                System.out.print(str.charAt(i));
    }
      
    /* Driver program*/
    public static void main(String args[])
    {
        String str = "GeeksforGeeks";
        printDistinct(str);
    }
}
// This code is contributed by Sumit Ghosh


Python3
# Python3 program to print distinct
# characters of a string.
NO_OF_CHARS = 256
 
# Print duplicates present in the
# passed string
def printDistinct(str):
 
    # Create an array of size 256 and
    # count of every character in it
    count = [0] * NO_OF_CHARS
 
    # Count array with frequency of
    # characters
    for i in range (len(str)):
        if(str[i] != ' '):
            count[ord(str[i])] += 1
    n = i
 
    # Print characters having count
    # more than 0
    for i in range(n):
        if (count[ord(str[i])] == 1):
            print (str[i], end = "")
 
# Driver Code
if __name__ == "__main__":
 
    str = "GeeksforGeeks"
    printDistinct(str)
     
# This code is contributed by ita_c


C#
// C# program to print distinct characters
// of a string.
using System;
 
public class GFG {
     
    static int NO_OF_CHARS = 256;
     
    /* Print duplicates present in the
    passed string */
    static void printDistinct(String str)
    {
         
        // Create an array of size 256 and
        // count of every character in it
        int[] count = new int[NO_OF_CHARS];
     
        /* Count array with frequency of
        characters */
        int i;
         
        for (i = 0; i < str.Length; i++)
            if(str[i]!=' ')
                count[(int)str[i]]++;
                 
        int n = i;
     
        // Print characters having count
        // more than 0
        for (i = 0; i < n; i++)
            if (count[(int)str[i]] == 1)
                Console.Write(str[i]);
    }
     
    /* Driver program*/
    public static void Main()
    {
        String str = "GeeksforGeeks";
         
        printDistinct(str);
    }
}
 
// This code is contributed by parashar.


Javascript


C++
// C++ program to find all distinct characters
// in a string
#include 
using namespace std;
const int MAX_CHAR = 256;
 
// Function to print distinct characters in
// given string str[]
void printDistinct(string str)
{
    int n = str.length();
 
    // count[x] is going to store count of
    // character 'x' in str. If x is not present,
    // then it is going to store 0.
    int count[MAX_CHAR];
 
    // index[x] is going to store index of character
    // 'x' in str. If x is not present or x is
    // more than once, then it is going to store a value
    // (for example, length of string) that cannot be
    // a valid index in str[]
    int index[MAX_CHAR];
 
    // Initialize counts of all characters and indexes
    // of distinct characters.
    for (int i = 0; i < MAX_CHAR; i++)
    {
        count[i] = 0;
        index[i] = n; // A value more than any index
                      // in str[]
    }
 
    // Traverse the input string
    for (int i = 0; i < n; i++)
    {
        // Find current character and increment its
        // count
        char x = str[i];
        ++count[x];
 
        // If this is first occurrence, then set value
        // in index as index of it.
        if (count[x] == 1 && x !=' ')
            index[x] = i;
 
        // If character repeats, then remove it from
        // index[]
        if (count[x] == 2)
            index[x] = n;
    }
 
    // Since size of index is constant, below operations
    // take constant time.
    sort(index, index+MAX_CHAR);
    for (int i=0; i


Java
// Java program to print distinct characters of
// a string.
import java.util.Arrays;
 
public class GFG {
     
    static final int MAX_CHAR = 256;
      
    // Function to print distinct characters in
    // given string str[]
    static void printDistinct(String str)
    {
        int n = str.length();
      
        // count[x] is going to store count of
        // character 'x' in str. If x is not present,
        // then it is going to store 0.
        int[] count = new int[MAX_CHAR];
      
        // index[x] is going to store index of character
        // 'x' in str. If x is not present or x is
        // more than once, then it is going to store a
        // value (for example, length of string) that
        // cannot be a valid index in str[]
        int[] index = new int[MAX_CHAR];
      
        // Initialize counts of all characters and
        // indexes of distinct characters.
        for (int i = 0; i < MAX_CHAR; i++)
        {
            count[i] = 0;
            index[i] = n; // A value more than any
                          // index in str[]
        }
      
        // Traverse the input string
        for (int i = 0; i < n; i++)
        {
            // Find current character and increment
            // its count
            char x = str.charAt(i);
            ++count[x];
      
            // If this is first occurrence, then set
            // value in index as index of it.
            if (count[x] == 1 && x !=' ')
                index[x] = i;
      
            // If character repeats, then remove it
            // from index[]
            if (count[x] == 2)
                index[x] = n;
        }
      
        // Since size of index is constant, below
        // operations take constant time.
        Arrays.sort(index);
         
        for (int i = 0; i < MAX_CHAR && index[i] != n;
                                                  i++)
           System.out.print(str.charAt(index[i]));
    }
      
    // Driver code
    public static void main(String args[])
    {
        String str = "GeeksforGeeks";
        printDistinct(str);
    }
}
// This code is contributed by Sumit Ghosh


Python
# Python3 program to find all distinct characters
# in a String
 
MAX_CHAR = 256
 
# Function to prdistinct characters in
# given Str[]
def printDistinct(Str):
 
    n = len(Str)
 
    # count[x] is going to store count of
    # character 'x' in Str. If x is not present,
    # then it is going to store 0.
    count = [0 for i in range(MAX_CHAR)]
 
    # index[x] is going to store index of character
    # 'x' in Str. If x is not present or x is
    # more than once, then it is going to store a value
    # (for example, length of String) that cannot be
    # a valid index in Str[]
    index = [n for i in range(MAX_CHAR)]
 
 
    # Traverse the input String
    for i in range(n):
         
        # Find current character and increment its
        # count
        x = ord(Str[i])
        count[x] += 1
 
        # If this is first occurrence, then set value
        # in index as index of it.
        if (count[x] == 1 and x !=' '):
            index[x] = i
 
        # If character repeats, then remove it from
        # index[]
        if (count[x] == 2):
            index[x] = n
 
 
    # Since size of index is constant, below operations
    # take constant time.
    index=sorted(index)
 
    for i in range(MAX_CHAR):
        if index[i] == n:
            break
        print(Str[index[i]],end="")
 
# Driver code
 
Str = "GeeksforGeeks"
printDistinct(Str)
 
# This code is contributed by mohit kumar 29


C#
// C# program to print distinct characters of
// a string.
using System;
 
public class GFG {
     
    static int MAX_CHAR = 256;
     
    // Function to print distinct characters in
    // given string str[]
    static void printDistinct(string str)
    {
        int n = str.Length;
     
        // count[x] is going to store count of
        // character 'x' in str. If x is not
        // present, then it is going to store 0.
        int []count = new int[MAX_CHAR];
     
        // index[x] is going to store index of
        // character 'x' in str. If x is not
        // present or x is more than once, then
        // it is going to store a value (for
        // example, length of string) that
        // cannot be a valid index in str[]
        int []index = new int[MAX_CHAR];
     
        // Initialize counts of all characters
        // and indexes of distinct characters.
        for (int i = 0; i < MAX_CHAR; i++)
        {
            count[i] = 0;
             
            // A value more than any index
            // in str[]
            index[i] = n;
                         
        }
     
        // Traverse the input string
        for (int i = 0; i < n; i++)
        {
            // Find current character and
            // increment its count
            char x = str[i];
            ++count[x];
     
            // If this is first occurrence, then
            // set value in index as index of it.
            if (count[x] == 1 && x !=' ')
                index[x] = i;
     
            // If character repeats, then remove
            // it from index[]
            if (count[x] == 2)
                index[x] = n;
        }
     
        // Since size of index is constant, below
        // operations take constant time.
        Array.Sort(index);
         
        for (int i = 0; i < MAX_CHAR &&
                              index[i] != n; i++)
        Console.Write(str[index[i]]);
    }
     
    // Driver code
    public static void Main()
    {
        string str = "GeeksforGeeks";
        printDistinct(str);
    }
}
 
// This code is contributed by nitin mittal.


Javascript


输出:

for

方法 3(O(n) 并且需要一次遍历)
这个想法是使用两个大小为 256 的辅助数组(假设字符使用 8 位存储)。

  1. 将 count[] 中的所有值初始化为 0,将 index[] 中的所有值初始化为 n,其中 n 是字符串 的长度。
  2. 遍历输入字符串str 并对每个字符c = str[i] 执行以下操作。
    • 增量计数[x]。
    • 如果 count[x] 为 1,则将 x 的索引存储在 index[x] 中,即 index[x] = i
    • 如果 count[x] 为 2,则从 index[] 中移除 x,即 index[x] = n
  3. 现在 index[] 具有所有不同字符的索引。使用它对索引进行排序并打印字符。请注意,假设字符数是固定的(通常为 256),此步骤需要 O(1) 时间

下面是上述想法的实现。

C++

// C++ program to find all distinct characters
// in a string
#include 
using namespace std;
const int MAX_CHAR = 256;
 
// Function to print distinct characters in
// given string str[]
void printDistinct(string str)
{
    int n = str.length();
 
    // count[x] is going to store count of
    // character 'x' in str. If x is not present,
    // then it is going to store 0.
    int count[MAX_CHAR];
 
    // index[x] is going to store index of character
    // 'x' in str. If x is not present or x is
    // more than once, then it is going to store a value
    // (for example, length of string) that cannot be
    // a valid index in str[]
    int index[MAX_CHAR];
 
    // Initialize counts of all characters and indexes
    // of distinct characters.
    for (int i = 0; i < MAX_CHAR; i++)
    {
        count[i] = 0;
        index[i] = n; // A value more than any index
                      // in str[]
    }
 
    // Traverse the input string
    for (int i = 0; i < n; i++)
    {
        // Find current character and increment its
        // count
        char x = str[i];
        ++count[x];
 
        // If this is first occurrence, then set value
        // in index as index of it.
        if (count[x] == 1 && x !=' ')
            index[x] = i;
 
        // If character repeats, then remove it from
        // index[]
        if (count[x] == 2)
            index[x] = n;
    }
 
    // Since size of index is constant, below operations
    // take constant time.
    sort(index, index+MAX_CHAR);
    for (int i=0; i

Java

// Java program to print distinct characters of
// a string.
import java.util.Arrays;
 
public class GFG {
     
    static final int MAX_CHAR = 256;
      
    // Function to print distinct characters in
    // given string str[]
    static void printDistinct(String str)
    {
        int n = str.length();
      
        // count[x] is going to store count of
        // character 'x' in str. If x is not present,
        // then it is going to store 0.
        int[] count = new int[MAX_CHAR];
      
        // index[x] is going to store index of character
        // 'x' in str. If x is not present or x is
        // more than once, then it is going to store a
        // value (for example, length of string) that
        // cannot be a valid index in str[]
        int[] index = new int[MAX_CHAR];
      
        // Initialize counts of all characters and
        // indexes of distinct characters.
        for (int i = 0; i < MAX_CHAR; i++)
        {
            count[i] = 0;
            index[i] = n; // A value more than any
                          // index in str[]
        }
      
        // Traverse the input string
        for (int i = 0; i < n; i++)
        {
            // Find current character and increment
            // its count
            char x = str.charAt(i);
            ++count[x];
      
            // If this is first occurrence, then set
            // value in index as index of it.
            if (count[x] == 1 && x !=' ')
                index[x] = i;
      
            // If character repeats, then remove it
            // from index[]
            if (count[x] == 2)
                index[x] = n;
        }
      
        // Since size of index is constant, below
        // operations take constant time.
        Arrays.sort(index);
         
        for (int i = 0; i < MAX_CHAR && index[i] != n;
                                                  i++)
           System.out.print(str.charAt(index[i]));
    }
      
    // Driver code
    public static void main(String args[])
    {
        String str = "GeeksforGeeks";
        printDistinct(str);
    }
}
// This code is contributed by Sumit Ghosh

Python

# Python3 program to find all distinct characters
# in a String
 
MAX_CHAR = 256
 
# Function to prdistinct characters in
# given Str[]
def printDistinct(Str):
 
    n = len(Str)
 
    # count[x] is going to store count of
    # character 'x' in Str. If x is not present,
    # then it is going to store 0.
    count = [0 for i in range(MAX_CHAR)]
 
    # index[x] is going to store index of character
    # 'x' in Str. If x is not present or x is
    # more than once, then it is going to store a value
    # (for example, length of String) that cannot be
    # a valid index in Str[]
    index = [n for i in range(MAX_CHAR)]
 
 
    # Traverse the input String
    for i in range(n):
         
        # Find current character and increment its
        # count
        x = ord(Str[i])
        count[x] += 1
 
        # If this is first occurrence, then set value
        # in index as index of it.
        if (count[x] == 1 and x !=' '):
            index[x] = i
 
        # If character repeats, then remove it from
        # index[]
        if (count[x] == 2):
            index[x] = n
 
 
    # Since size of index is constant, below operations
    # take constant time.
    index=sorted(index)
 
    for i in range(MAX_CHAR):
        if index[i] == n:
            break
        print(Str[index[i]],end="")
 
# Driver code
 
Str = "GeeksforGeeks"
printDistinct(Str)
 
# This code is contributed by mohit kumar 29

C#

// C# program to print distinct characters of
// a string.
using System;
 
public class GFG {
     
    static int MAX_CHAR = 256;
     
    // Function to print distinct characters in
    // given string str[]
    static void printDistinct(string str)
    {
        int n = str.Length;
     
        // count[x] is going to store count of
        // character 'x' in str. If x is not
        // present, then it is going to store 0.
        int []count = new int[MAX_CHAR];
     
        // index[x] is going to store index of
        // character 'x' in str. If x is not
        // present or x is more than once, then
        // it is going to store a value (for
        // example, length of string) that
        // cannot be a valid index in str[]
        int []index = new int[MAX_CHAR];
     
        // Initialize counts of all characters
        // and indexes of distinct characters.
        for (int i = 0; i < MAX_CHAR; i++)
        {
            count[i] = 0;
             
            // A value more than any index
            // in str[]
            index[i] = n;
                         
        }
     
        // Traverse the input string
        for (int i = 0; i < n; i++)
        {
            // Find current character and
            // increment its count
            char x = str[i];
            ++count[x];
     
            // If this is first occurrence, then
            // set value in index as index of it.
            if (count[x] == 1 && x !=' ')
                index[x] = i;
     
            // If character repeats, then remove
            // it from index[]
            if (count[x] == 2)
                index[x] = n;
        }
     
        // Since size of index is constant, below
        // operations take constant time.
        Array.Sort(index);
         
        for (int i = 0; i < MAX_CHAR &&
                              index[i] != n; i++)
        Console.Write(str[index[i]]);
    }
     
    // Driver code
    public static void Main()
    {
        string str = "GeeksforGeeks";
        printDistinct(str);
    }
}
 
// This code is contributed by nitin mittal.

Javascript


输出:

for

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程