📌  相关文章
📜  确定字符串是否具有所有唯一字符

📅  最后修改于: 2021-05-25 03:44:21             🧑  作者: Mango

给定一个字符串,请确定该字符串是否具有所有唯一字符。

例子 :

Input : abcd10jk
Output : true

Input : hutg9mnd!nk9
Output : false

方法1 –蛮力技术:使用变量i和j运行2个循环。比较str [i]和str [j]。如果它们在任何时候都相等,则返回false。
时间复杂度:O(n 2 )

C++
// C++ program to illustrate string
// with unique characters using
// brute force technique
#include 
using namespace std;
 
bool uniqueCharacters(string str)
{
 
    // If at any time we encounter 2
    // same characters, return false
    for (int i = 0; i < str.length() - 1; i++) {
        for (int j = i + 1; j < str.length(); j++) {
            if (str[i] == str[j]) {
                return false;
            }
        }
    }
 
    // If no duplicate characters encountered,
    // return true
    return true;
}
 
// driver code
int main()
{
    string str = "GeeksforGeeks";
 
    if (uniqueCharacters(str)) {
        cout << "The String " << str
             << " has all unique characters\n";
    }
    else {
        cout << "The String " << str
             << " has duplicate characters\n";
    }
    return 0;
}
// This code is contributed by Divyam Madaan


Java
// Java program to illustrate string with
// unique characters using brute force technique
import java.util.*;
 
class GfG {
    boolean uniqueCharacters(String str)
    {
        // If at any time we encounter 2 same
        // characters, return false
        for (int i = 0; i < str.length(); i++)
            for (int j = i + 1; j < str.length(); j++)
                if (str.charAt(i) == str.charAt(j))
                    return false;
 
        // If no duplicate characters encountered,
        // return true
        return true;
    }
 
    public static void main(String args[])
    {
        GfG obj = new GfG();
        String input = "GeeksforGeeks";
 
        if (obj.uniqueCharacters(input))
            System.out.println("The String " + input + " has all unique characters");
        else
            System.out.println("The String " + input + " has duplicate characters");
    }
}


Python3
# Python program to illustrate string
# with unique characters using
# brute force technique
 
def uniqueCharacters(str):
     
    # If at any time we encounter 2
    # same characters, return false
    for i in range(len(str)):
        for j in range(i + 1,len(str)):
            if(str[i] == str[j]):
                return False;
 
    # If no duplicate characters
    # encountered, return true
    return True;
 
 
# Driver Code
str = "GeeksforGeeks";
 
if(uniqueCharacters(str)):
    print("The String ", str," has all unique characters");
else:
    print("The String ", str, " has duplicate characters");
 
# This code contributed by PrinciRaj1992


C#
// C# program to illustrate string with
// unique characters using brute force
// technique
using System;
 
public class GFG {
 
    static bool uniqueCharacters(String str)
    {
 
        // If at any time we encounter 2
        // same characters, return false
        for (int i = 0; i < str.Length; i++)
            for (int j = i + 1; j < str.Length; j++)
                if (str[i] == str[j])
                    return false;
 
        // If no duplicate characters
        // encountered, return true
        return true;
    }
 
    public static void Main()
    {
        string input = "GeeksforGeeks";
 
        if (uniqueCharacters(input) == true)
            Console.WriteLine("The String " + input
                              + " has all unique characters");
        else
            Console.WriteLine("The String " + input
                              + " has duplicate characters");
    }
}
 
// This code is contributed by shiv_bhakt.


PHP


Javascript


C++
// C++ program to illustrate string
// with unique characters using
// brute force technique
#include 
using namespace std;
 
bool uniqueCharacters(string str)
{
 
    // Using sorting
    sort(str.begin(), str.end());
 
    for (int i = 0; i < str.length()-1; i++) {
 
        // if at any time, 2 adjacent
        // elements become equal,
        // return false
        if (str[i] == str[i + 1]) {
            return false;
        }
    }
    return true;
}
 
// driver code
int main()
{
 
    string str = "GeeksforGeeks";
 
    if (uniqueCharacters(str)) {
        cout << "The String " << str
             << " has all unique characters\n";
    }
    else {
 
        cout << "The String " << str
             << " has duplicate characters\n";
    }
    return 0;
}
// This code is contributed by Divyam Madaan


Java
// Java program to check string with unique
// characters using sorting technique
import java.util.*;
 
class GfG {
    /* Convert the string to character array
       for sorting */
    boolean uniqueCharacters(String str)
    {
        char[] chArray = str.toCharArray();
 
        // Using sorting
        // Arrays.sort() uses binarySort in the background
        // for non-primitives which is of O(nlogn) time complexity
        Arrays.sort(chArray);
 
        for (int i = 0; i < chArray.length - 1; i++) {
            // if the adjacent elements are not
            // equal, move to next element
            if (chArray[i] != chArray[i + 1])
                continue;
 
            // if at any time, 2 adjacent elements
            // become equal, return false
            else
                return false;
        }
        return true;
    }
 
    // Driver code
    public static void main(String args[])
    {
        GfG obj = new GfG();
        String input = "GeeksforGeeks";
 
        if (obj.uniqueCharacters(input))
            System.out.println("The String " + input
                               + " has all unique characters");
        else
            System.out.println("The String " + input
                               + " has duplicate characters");
    }
}


Python3
# Python3 program to illustrate string
# with unique characters using
# brute force technique
def uniqueCharacters(st):
 
    # Using sorting
    sorted(st)
 
    for i in range(len(st)-1):
 
        # if at any time, 2 adjacent
        # elements become equal,
        # return false
        if (st[i] == st[i + 1]) :
            return False
             
    return True
 
# Driver code
if __name__=='__main__':
 
    st = "GeeksforGeeks"
 
    if (uniqueCharacters(st)) :
        print("The String",st,"has all unique characters\n")
     
    else :
        print("The String",st,"has duplicate characters\n")
     
 
# This code is contributed by AbhiThakur


C#
// C# program to check string with unique
// characters using sorting technique
using System;
 
public class GFG {
 
    /* Convert the string to character array
    for sorting */
    static bool uniqueCharacters(String str)
    {
        char[] chArray = str.ToCharArray();
 
        // Using sorting
        Array.Sort(chArray);
 
        for (int i = 0; i < chArray.Length - 1; i++) {
 
            // if the adjacent elements are not
            // equal, move to next element
            if (chArray[i] != chArray[i + 1])
                continue;
 
            // if at any time, 2 adjacent elements
            // become equal, return false
            else
                return false;
        }
 
        return true;
    }
 
    // Driver code
    public static void Main()
    {
        string input = "GeeksforGeeks";
 
        if (uniqueCharacters(input) == true)
            Console.WriteLine("The String " + input
                              + " has all unique characters");
        else
            Console.WriteLine("The String " + input
                              + " has duplicate characters");
    }
}
 
// This code is contributed by shiv_bhakt.


Javascript


C++
#include 
#include 
using namespace std;
 
const int MAX_CHAR = 256;
 
bool uniqueCharacters(string str)
{
 
    // If length is greater than 265,
    // some characters must have been repeated
    if (str.length() > MAX_CHAR)
        return false;
 
    bool chars[MAX_CHAR] = { 0 };
    for (int i = 0; i < str.length(); i++) {
        if (chars[int(str[i])] == true)
            return false;
 
        chars[int(str[i])] = true;
    }
    return true;
}
 
// driver code
int main()
{
    string str = "GeeksforGeeks";
 
    if (uniqueCharacters(str)) {
        cout << "The String " << str
             << " has all unique characters\n";
    }
    else {
 
        cout << "The String " << str
             << " has duplicate characters\n";
    }
    return 0;
}
// This code is contributed by Divyam Madaan


Java
// Java program to illustrate String With
// Unique Characters using data structure
import java.util.*;
 
class GfG {
    int MAX_CHAR = 256;
 
    boolean uniqueCharacters(String str)
    {
        // If length is greater than 256,
        // some characters must have been repeated
        if (str.length() > MAX_CHAR)
            return false;
 
        boolean[] chars = new boolean[MAX_CHAR];
        Arrays.fill(chars, false);
 
        for (int i = 0; i < str.length(); i++) {
            int index = (int)str.charAt(i);
 
            /* If the value is already true, string
               has duplicate characters, return false */
            if (chars[index] == true)
                return false;
 
            chars[index] = true;
        }
 
        /* No duplicates encountered, return true */
        return true;
    }
 
    // Driver code
    public static void main(String args[])
    {
        GfG obj = new GfG();
        String input = "GeeksforGeeks";
 
        if (obj.uniqueCharacters(input))
            System.out.println("The String " + input
                               + " has all unique characters");
        else
            System.out.println("The String " + input
                               + " has duplicate characters");
    }
}


Python3
# Python program to illustrate
# string with unique characters
# using data structure
MAX_CHAR = 256;
 
def uniqueCharacters(str):
   
    # If length is greater than 256,
    # some characters must have
    # been repeated
    if (len(str) > MAX_CHAR):
        return False;
 
    chars = [False] * MAX_CHAR;
 
    for i in range(len(str)):
        index = ord(str[i]);
 
        '''
         * If the value is already True,
         string has duplicate characters,
         return False'''
        if (chars[index] == True):
            return False;
 
        chars[index] = True;
 
    ''' No duplicates encountered,
        return True '''
    return True;
 
# Driver code
if __name__ == '__main__':
   
    input = "GeeksforGeeks";
    if (uniqueCharacters(input)):
        print("The String", input,
              "has all unique characters");
    else:
        print("The String", input,
              "has duplicate characters");
 
# This code is contributed by shikhasingrajput


C#
// C# program to illustrate String With
// Unique Characters using data structure
using System;
 
class GfG {
    static int MAX_CHAR = 256;
 
    bool uniqueCharacters(String str)
    {
        // If length is greater than 256,
        // some characters must have been repeated
        if (str.Length > MAX_CHAR)
            return false;
 
        bool[] chars = new bool[MAX_CHAR];
        for (int i = 0; i < MAX_CHAR; i++) {
            chars[i] = false;
        }
        for (int i = 0; i < str.Length; i++) {
            int index = (int)str[i];
 
            /* If the value is already true, string
            has duplicate characters, return false */
            if (chars[index] == true)
                return false;
 
            chars[index] = true;
        }
 
        /* No duplicates encountered, return true */
        return true;
    }
 
    // Driver code
    public static void Main(String[] args)
    {
        GfG obj = new GfG();
        String input = "GeeksforGeeks";
 
        if (obj.uniqueCharacters(input))
            Console.WriteLine("The String " + input
                              + " has all unique characters");
        else
            Console.WriteLine("The String " + input
                              + " has duplicate characters");
    }
}
 
// This code has been contributed by 29AjayKumar


Javascript


C++
// C++ program to illustrate string
// with unique characters using
// brute force technique
#include 
using namespace std;
 
bool uniqueCharacters(string str)
{
 
    // Assuming string can have characters
    // a-z, this has 32 bits set to 0
    int checker = 0;
 
    for (int i = 0; i < str.length(); i++) {
 
        int bitAtIndex = str[i] - 'a';
 
        // if that bit is already set in
        // checker, return false
        if ((checker & (1 << bitAtIndex)) > 0) {
            return false;
        }
 
        // otherwise update and continue by
        // setting that bit in the checker
        checker = checker | (1 << bitAtIndex);
    }
 
    // no duplicates encountered, return true
    return true;
}
 
// driver code
int main()
{
 
    string str = "GeeksforGeeks";
 
    if (uniqueCharacters(str)) {
        cout << "The String " << str
             << " has all unique characters\n";
    }
    else {
        cout << "The String " << str
             << " has duplicate characters\n";
    }
    return 0;
}
// This code is contributed by Divyam Madaan


Java
// Java program to illustrate String with unique
// characters without using any data structure
import java.util.*;
 
class GfG {
    boolean uniqueCharacters(String str)
    {
        // Assuming string can have characters a-z
        // this has 32 bits set to 0
        int checker = 0;
 
        for (int i = 0; i < str.length(); i++) {
            int bitAtIndex = str.charAt(i) - 'a';
 
            // if that bit is already set in checker,
            // return false
            if ((checker & (1 << bitAtIndex)) > 0)
                return false;
 
            // otherwise update and continue by
            // setting that bit in the checker
            checker = checker | (1 << bitAtIndex);
        }
 
        // no duplicates encountered, return true
        return true;
    }
 
    // Driver Code
    public static void main(String args[])
    {
        GfG obj = new GfG();
        String input = "GeekforGeeks";
 
        if (obj.uniqueCharacters(input))
            System.out.println("The String " + input
                               + " has all unique characters");
        else
            System.out.println("The String " + input
                               + " has duplicate characters");
    }
}


Python3
# Python3 program to illustrate String with unique
# characters without using any data structure
import math
 
def uniqueCharacters(str):
     
    # Assuming string can have characters
    # a-z this has 32 bits set to 0
    checker = 0
     
    for i in range(len(str)):
        bitAtIndex = ord(str[i]) - ord('a')
 
        # If that bit is already set in
        # checker, return False
        if ((bitAtIndex) > 0):
            if ((checker & ((1 << bitAtIndex))) > 0):
                return False
                 
            # Otherwise update and continue by
            # setting that bit in the checker
            checker = checker | (1 << bitAtIndex)
 
    # No duplicates encountered, return True
    return True
 
# Driver Code
if __name__ == '__main__':
     
    input = "GeekforGeeks"
 
    if (uniqueCharacters(input)):
        print("The String " + input +
              " has all unique characters")
    else:
        print("The String " + input +
              " has duplicate characters")
 
# This code is contributed by Princi Singh


C#
// C# program to illustrate String
// with unique characters without
// using any data structure
using System;
 
class GFG {
    public virtual bool uniqueCharacters(string str)
    {
        // Assuming string can have
        // characters a-z this has
        // 32 bits set to 0
        int checker = 0;
 
        for (int i = 0; i < str.Length; i++) {
            int bitAtIndex = str[i] - 'a';
 
            // if that bit is already set
            // in checker, return false
            if ((checker & (1 << bitAtIndex)) > 0) {
                return false;
            }
 
            // otherwise update and continue by
            // setting that bit in the checker
            checker = checker | (1 << bitAtIndex);
        }
 
        // no duplicates encountered,
        // return true
        return true;
    }
 
    // Driver Code
    public static void Main(string[] args)
    {
        GFG obj = new GFG();
        string input = "GeekforGeeks";
 
        if (obj.uniqueCharacters(input)) {
            Console.WriteLine("The String " + input + " has all unique characters");
        }
        else {
            Console.WriteLine("The String " + input + " has duplicate characters");
        }
    }
}
 
// This code is contributed by Shrikant13


PHP
 0)
        {
            return false;
        }
         
    // otherwise update and continue by
    // setting that bit in the checker
    $checker = $checker |
               (1 << $bitAtIndex);
    }
     
    // no duplicates encountered,
    // return true
    return true;
}
 
// Driver Code
$str = "GeeksforGeeks";
 
if(uniqueCharacters($str))
{
    echo "The String ", $str,
         " has all unique characters\n";
}
else
{
    echo "The String ", $str,
         " has duplicate characters\n";
}
 
// This code is contributed by ajit
?>


Javascript


Java
import java.util.Collections;
import java.util.stream.Collectors;
class GfG {
    boolean uniqueCharacters(String s)
    {
        // If at any character more than once create another stream
        // stream count more than 0, return false
        return s.chars().filter(e-> Collections.frequency(s.chars().boxed().collect(Collectors.toList()), e) > 1).count() > 1 ? false: true;
    }
  
    public static void main(String args[])
    {
        GfG obj = new GfG();
        String input = "GeeksforGeeks";
  
        if (obj.uniqueCharacters(input))
            System.out.println("The String " + input + " has all unique characters");
        else
            System.out.println("The String " + input + " has duplicate characters");
    }
}
 
//Write Java code here


Python3
# Python3 program to illustrate String with unique
# characters
def uniqueCharacters(str):
   
    # Converting string to set
    setstring = set(str)
     
    # If length of set is equal to len of string
    # then it will have unique characters
    if(len(setstring) == len(str)):
        return True
       
    return False
 
 
# Driver Code
if __name__ == '__main__':
 
    input = "GeeksforGeeks"
 
    if (uniqueCharacters(input)):
        print("The String " + input +
              " has all unique characters")
    else:
        print("The String " + input +
              " has duplicate characters")
 
# This code is contributed by vikkycirus


输出 :

The String GeeksforGeeks has duplicate characters

注意:请注意,该程序区分大小写。

方法2 -排序:基于字符的ASCII值使用排序
时间复杂度:O(n log n)

C++

// C++ program to illustrate string
// with unique characters using
// brute force technique
#include 
using namespace std;
 
bool uniqueCharacters(string str)
{
 
    // Using sorting
    sort(str.begin(), str.end());
 
    for (int i = 0; i < str.length()-1; i++) {
 
        // if at any time, 2 adjacent
        // elements become equal,
        // return false
        if (str[i] == str[i + 1]) {
            return false;
        }
    }
    return true;
}
 
// driver code
int main()
{
 
    string str = "GeeksforGeeks";
 
    if (uniqueCharacters(str)) {
        cout << "The String " << str
             << " has all unique characters\n";
    }
    else {
 
        cout << "The String " << str
             << " has duplicate characters\n";
    }
    return 0;
}
// This code is contributed by Divyam Madaan

Java

// Java program to check string with unique
// characters using sorting technique
import java.util.*;
 
class GfG {
    /* Convert the string to character array
       for sorting */
    boolean uniqueCharacters(String str)
    {
        char[] chArray = str.toCharArray();
 
        // Using sorting
        // Arrays.sort() uses binarySort in the background
        // for non-primitives which is of O(nlogn) time complexity
        Arrays.sort(chArray);
 
        for (int i = 0; i < chArray.length - 1; i++) {
            // if the adjacent elements are not
            // equal, move to next element
            if (chArray[i] != chArray[i + 1])
                continue;
 
            // if at any time, 2 adjacent elements
            // become equal, return false
            else
                return false;
        }
        return true;
    }
 
    // Driver code
    public static void main(String args[])
    {
        GfG obj = new GfG();
        String input = "GeeksforGeeks";
 
        if (obj.uniqueCharacters(input))
            System.out.println("The String " + input
                               + " has all unique characters");
        else
            System.out.println("The String " + input
                               + " has duplicate characters");
    }
}

Python3

# Python3 program to illustrate string
# with unique characters using
# brute force technique
def uniqueCharacters(st):
 
    # Using sorting
    sorted(st)
 
    for i in range(len(st)-1):
 
        # if at any time, 2 adjacent
        # elements become equal,
        # return false
        if (st[i] == st[i + 1]) :
            return False
             
    return True
 
# Driver code
if __name__=='__main__':
 
    st = "GeeksforGeeks"
 
    if (uniqueCharacters(st)) :
        print("The String",st,"has all unique characters\n")
     
    else :
        print("The String",st,"has duplicate characters\n")
     
 
# This code is contributed by AbhiThakur

C#

// C# program to check string with unique
// characters using sorting technique
using System;
 
public class GFG {
 
    /* Convert the string to character array
    for sorting */
    static bool uniqueCharacters(String str)
    {
        char[] chArray = str.ToCharArray();
 
        // Using sorting
        Array.Sort(chArray);
 
        for (int i = 0; i < chArray.Length - 1; i++) {
 
            // if the adjacent elements are not
            // equal, move to next element
            if (chArray[i] != chArray[i + 1])
                continue;
 
            // if at any time, 2 adjacent elements
            // become equal, return false
            else
                return false;
        }
 
        return true;
    }
 
    // Driver code
    public static void Main()
    {
        string input = "GeeksforGeeks";
 
        if (uniqueCharacters(input) == true)
            Console.WriteLine("The String " + input
                              + " has all unique characters");
        else
            Console.WriteLine("The String " + input
                              + " has duplicate characters");
    }
}
 
// This code is contributed by shiv_bhakt.

Java脚本


输出:

The String GeeksforGeeks has duplicate characters

方法3 –使用额外的数据结构:此方法假定使用ASCII字符集(8位)。这个想法是为字符维护一个布尔数组。 256个索引表示256个字符。所有数组元素最初都设置为false。当我们遍历字符串,在索引处将true设置为等于字符的int值。如果在任何时候遇到数组值已经为真,则意味着具有该int值的字符将被重复。

时间复杂度: O(n)

C++

#include 
#include 
using namespace std;
 
const int MAX_CHAR = 256;
 
bool uniqueCharacters(string str)
{
 
    // If length is greater than 265,
    // some characters must have been repeated
    if (str.length() > MAX_CHAR)
        return false;
 
    bool chars[MAX_CHAR] = { 0 };
    for (int i = 0; i < str.length(); i++) {
        if (chars[int(str[i])] == true)
            return false;
 
        chars[int(str[i])] = true;
    }
    return true;
}
 
// driver code
int main()
{
    string str = "GeeksforGeeks";
 
    if (uniqueCharacters(str)) {
        cout << "The String " << str
             << " has all unique characters\n";
    }
    else {
 
        cout << "The String " << str
             << " has duplicate characters\n";
    }
    return 0;
}
// This code is contributed by Divyam Madaan

Java

// Java program to illustrate String With
// Unique Characters using data structure
import java.util.*;
 
class GfG {
    int MAX_CHAR = 256;
 
    boolean uniqueCharacters(String str)
    {
        // If length is greater than 256,
        // some characters must have been repeated
        if (str.length() > MAX_CHAR)
            return false;
 
        boolean[] chars = new boolean[MAX_CHAR];
        Arrays.fill(chars, false);
 
        for (int i = 0; i < str.length(); i++) {
            int index = (int)str.charAt(i);
 
            /* If the value is already true, string
               has duplicate characters, return false */
            if (chars[index] == true)
                return false;
 
            chars[index] = true;
        }
 
        /* No duplicates encountered, return true */
        return true;
    }
 
    // Driver code
    public static void main(String args[])
    {
        GfG obj = new GfG();
        String input = "GeeksforGeeks";
 
        if (obj.uniqueCharacters(input))
            System.out.println("The String " + input
                               + " has all unique characters");
        else
            System.out.println("The String " + input
                               + " has duplicate characters");
    }
}

Python3

# Python program to illustrate
# string with unique characters
# using data structure
MAX_CHAR = 256;
 
def uniqueCharacters(str):
   
    # If length is greater than 256,
    # some characters must have
    # been repeated
    if (len(str) > MAX_CHAR):
        return False;
 
    chars = [False] * MAX_CHAR;
 
    for i in range(len(str)):
        index = ord(str[i]);
 
        '''
         * If the value is already True,
         string has duplicate characters,
         return False'''
        if (chars[index] == True):
            return False;
 
        chars[index] = True;
 
    ''' No duplicates encountered,
        return True '''
    return True;
 
# Driver code
if __name__ == '__main__':
   
    input = "GeeksforGeeks";
    if (uniqueCharacters(input)):
        print("The String", input,
              "has all unique characters");
    else:
        print("The String", input,
              "has duplicate characters");
 
# This code is contributed by shikhasingrajput

C#

// C# program to illustrate String With
// Unique Characters using data structure
using System;
 
class GfG {
    static int MAX_CHAR = 256;
 
    bool uniqueCharacters(String str)
    {
        // If length is greater than 256,
        // some characters must have been repeated
        if (str.Length > MAX_CHAR)
            return false;
 
        bool[] chars = new bool[MAX_CHAR];
        for (int i = 0; i < MAX_CHAR; i++) {
            chars[i] = false;
        }
        for (int i = 0; i < str.Length; i++) {
            int index = (int)str[i];
 
            /* If the value is already true, string
            has duplicate characters, return false */
            if (chars[index] == true)
                return false;
 
            chars[index] = true;
        }
 
        /* No duplicates encountered, return true */
        return true;
    }
 
    // Driver code
    public static void Main(String[] args)
    {
        GfG obj = new GfG();
        String input = "GeeksforGeeks";
 
        if (obj.uniqueCharacters(input))
            Console.WriteLine("The String " + input
                              + " has all unique characters");
        else
            Console.WriteLine("The String " + input
                              + " has duplicate characters");
    }
}
 
// This code has been contributed by 29AjayKumar

Java脚本


输出:

The String GeeksforGeeks has duplicate characters

方法4 –没有额外的数据结构:该方法适用于字母为az的字符串。这种方法有点棘手。代替维护布尔型数组,我们维护一个称为checker(32 bits)的整数值。当我们遍历字符串,通过语句int bitAtIndex = str.charAt(i)-‘a’;找到相对于’a’的字符的int值
然后使用语句1 << bitAtIndex将该int值的位设置为1。
现在,如果该位已经在检查器中设置,则位AND操作将使检查器>0。在这种情况下,返回false。
其他更新检查程序,使用语句checker = checker |在该索引处使位1。 (1 << bitAtIndex);

时间复杂度:O(n)

C++

// C++ program to illustrate string
// with unique characters using
// brute force technique
#include 
using namespace std;
 
bool uniqueCharacters(string str)
{
 
    // Assuming string can have characters
    // a-z, this has 32 bits set to 0
    int checker = 0;
 
    for (int i = 0; i < str.length(); i++) {
 
        int bitAtIndex = str[i] - 'a';
 
        // if that bit is already set in
        // checker, return false
        if ((checker & (1 << bitAtIndex)) > 0) {
            return false;
        }
 
        // otherwise update and continue by
        // setting that bit in the checker
        checker = checker | (1 << bitAtIndex);
    }
 
    // no duplicates encountered, return true
    return true;
}
 
// driver code
int main()
{
 
    string str = "GeeksforGeeks";
 
    if (uniqueCharacters(str)) {
        cout << "The String " << str
             << " has all unique characters\n";
    }
    else {
        cout << "The String " << str
             << " has duplicate characters\n";
    }
    return 0;
}
// This code is contributed by Divyam Madaan

Java

// Java program to illustrate String with unique
// characters without using any data structure
import java.util.*;
 
class GfG {
    boolean uniqueCharacters(String str)
    {
        // Assuming string can have characters a-z
        // this has 32 bits set to 0
        int checker = 0;
 
        for (int i = 0; i < str.length(); i++) {
            int bitAtIndex = str.charAt(i) - 'a';
 
            // if that bit is already set in checker,
            // return false
            if ((checker & (1 << bitAtIndex)) > 0)
                return false;
 
            // otherwise update and continue by
            // setting that bit in the checker
            checker = checker | (1 << bitAtIndex);
        }
 
        // no duplicates encountered, return true
        return true;
    }
 
    // Driver Code
    public static void main(String args[])
    {
        GfG obj = new GfG();
        String input = "GeekforGeeks";
 
        if (obj.uniqueCharacters(input))
            System.out.println("The String " + input
                               + " has all unique characters");
        else
            System.out.println("The String " + input
                               + " has duplicate characters");
    }
}

Python3

# Python3 program to illustrate String with unique
# characters without using any data structure
import math
 
def uniqueCharacters(str):
     
    # Assuming string can have characters
    # a-z this has 32 bits set to 0
    checker = 0
     
    for i in range(len(str)):
        bitAtIndex = ord(str[i]) - ord('a')
 
        # If that bit is already set in
        # checker, return False
        if ((bitAtIndex) > 0):
            if ((checker & ((1 << bitAtIndex))) > 0):
                return False
                 
            # Otherwise update and continue by
            # setting that bit in the checker
            checker = checker | (1 << bitAtIndex)
 
    # No duplicates encountered, return True
    return True
 
# Driver Code
if __name__ == '__main__':
     
    input = "GeekforGeeks"
 
    if (uniqueCharacters(input)):
        print("The String " + input +
              " has all unique characters")
    else:
        print("The String " + input +
              " has duplicate characters")
 
# This code is contributed by Princi Singh

C#

// C# program to illustrate String
// with unique characters without
// using any data structure
using System;
 
class GFG {
    public virtual bool uniqueCharacters(string str)
    {
        // Assuming string can have
        // characters a-z this has
        // 32 bits set to 0
        int checker = 0;
 
        for (int i = 0; i < str.Length; i++) {
            int bitAtIndex = str[i] - 'a';
 
            // if that bit is already set
            // in checker, return false
            if ((checker & (1 << bitAtIndex)) > 0) {
                return false;
            }
 
            // otherwise update and continue by
            // setting that bit in the checker
            checker = checker | (1 << bitAtIndex);
        }
 
        // no duplicates encountered,
        // return true
        return true;
    }
 
    // Driver Code
    public static void Main(string[] args)
    {
        GFG obj = new GFG();
        string input = "GeekforGeeks";
 
        if (obj.uniqueCharacters(input)) {
            Console.WriteLine("The String " + input + " has all unique characters");
        }
        else {
            Console.WriteLine("The String " + input + " has duplicate characters");
        }
    }
}
 
// This code is contributed by Shrikant13

的PHP

 0)
        {
            return false;
        }
         
    // otherwise update and continue by
    // setting that bit in the checker
    $checker = $checker |
               (1 << $bitAtIndex);
    }
     
    // no duplicates encountered,
    // return true
    return true;
}
 
// Driver Code
$str = "GeeksforGeeks";
 
if(uniqueCharacters($str))
{
    echo "The String ", $str,
         " has all unique characters\n";
}
else
{
    echo "The String ", $str,
         " has duplicate characters\n";
}
 
// This code is contributed by ajit
?>

Java脚本


输出 :

The String GeekforGeeks has duplicate characters

练习:上面的程序区分大小写,您可以尝试制作不区分大小写的相同程序,即Geeks和GEeks都给出相似的输出。

使用Java Stream:

Java

import java.util.Collections;
import java.util.stream.Collectors;
class GfG {
    boolean uniqueCharacters(String s)
    {
        // If at any character more than once create another stream
        // stream count more than 0, return false
        return s.chars().filter(e-> Collections.frequency(s.chars().boxed().collect(Collectors.toList()), e) > 1).count() > 1 ? false: true;
    }
  
    public static void main(String args[])
    {
        GfG obj = new GfG();
        String input = "GeeksforGeeks";
  
        if (obj.uniqueCharacters(input))
            System.out.println("The String " + input + " has all unique characters");
        else
            System.out.println("The String " + input + " has duplicate characters");
    }
}
 
//Write Java code here

参考:
Gayle破解编码面试

方法5:在Python使用sets():

  • 将字符串转换为set。
  • 如果set的长度等于字符串的长度,则返回True否则为False。

下面是上述方法的实现

Python3

# Python3 program to illustrate String with unique
# characters
def uniqueCharacters(str):
   
    # Converting string to set
    setstring = set(str)
     
    # If length of set is equal to len of string
    # then it will have unique characters
    if(len(setstring) == len(str)):
        return True
       
    return False
 
 
# Driver Code
if __name__ == '__main__':
 
    input = "GeeksforGeeks"
 
    if (uniqueCharacters(input)):
        print("The String " + input +
              " has all unique characters")
    else:
        print("The String " + input +
              " has duplicate characters")
 
# This code is contributed by vikkycirus

输出:

The String GeeksforGeeks has duplicate characters

时间复杂度: O(nlogn)