📌  相关文章
📜  快速检查字符串中所有字符是否相同的方法

📅  最后修改于: 2021-05-30 10:43:58             🧑  作者: Mango

给定一个字符串,检查如果字符串的所有字符都是相同与否。

例子:

Input : s = "geeks"
Output : No

Input : s = "gggg" 
Output : Yes

简单的方法

查找字符串是否具有相同的字符。从索引1遍历整个字符串,并检查该字符是否与字符串的第一个字符匹配。如果是,则匹配直到字符串大小。如果否,则中断循环。

C++
// C++ program to find whether the string
// has all same characters or not.
#include 
using namespace std;
 
bool allCharactersSame(string s)
{
    int n = s.length();
    for (int i = 1; i < n; i++)
        if (s[i] != s[0])
            return false;
 
    return true;
}
 
// Driver code
int main()
{
    string s = "aaa";
    if (allCharactersSame(s))
        cout << "Yes";
    else
        cout << "No";
 
    return 0;
}


Java
// Java program to find whether the String
// has all same characters or not.
import java.io.*;
 
public class GFG{
 
static boolean allCharactersSame(String s)
{
    int n = s.length();
    for (int i = 1; i < n; i++)
        if (s.charAt(i) != s.charAt(0))
            return false;
         
    return true;
}
 
// Driver code
    static public void main (String[] args){
        String s = "aaa";
    if (allCharactersSame(s))
        System.out.println("Yes");
    else
        System.out.println("No");
         
    }
}
 
// This Code is contributed by vt_m.


Python3
# Python3 program to find whether the string
# has all same characters or not.
 
# Function to check the string has
# all same characters or not .
def allCharactersSame(s) :
    n = len(s)
    for i in range(1, n) :
        if s[i] != s[0] :
            return False
 
    return True
 
# Driver code
if __name__ == "__main__" :
     
    s = "aaa"
    if allCharactersSame(s) :
        print("Yes")
    else :
        print("No")
 
# This code is contributed by ANKITRAI1


C#
// C# program to find whether the string
// has all same characters or not.
using System;
 
public class GFG{
 
static bool allCharactersSame(string s)
{
    int n = s.Length;
    for (int i = 1; i < n; i++)
        if (s[i] != s[0])
            return false;
 
    return true;
}
 
// Driver code
    static public void Main (String []args){
        string s = "aaa";
    if (allCharactersSame(s))
        Console.WriteLine("Yes");
    else
        Console.WriteLine("No");
         
    }
}
 
// This code is contributed by vt_m.


PHP


Javascript


C++
// A quick C++ program to find whether the
// string has all same characters or not.
#include 
using namespace std;
 
bool allCharactersSame(string s)
{
    return (s.find_first_not_of(s[0]) == string::npos);
}
 
// Driver code
int main()
{
    string s = "aaa";
    if (allCharactersSame(s))
        cout << "Yes";
    else
        cout << "No";
 
    return 0;
}


C++
// C++ program for above approach
#include 
using namespace std;
 
// Function to check is all the
// characters in string are or not
void allCharactersSame(string s)
{
    set  s1;
   
    // Insert characters in the set
    for ( int i=0 ; i < s.length() ; i++)
        s1.insert(s[i]);
     
    // If all characters are same
    // Size of set will always be 1
    if ( s1.size() == 1 )
        cout << "YES";
    else
        cout << "NO";
}
 
// Driver code
int main()
{
    string str = "nnnn";
    allCharactersSame(str);
      return 0;
}


Java
// Java program for above approach
import java.io.*;
import java.util.*;
 
class GFG{
     
// Function to check is all the
// characters in string are or not
public static void allCharactersSame(String s)
{
    Set s1 = new HashSet();
     
    // Insert characters in the set
    for(int i = 0; i < s.length(); i++)
        s1.add(s.charAt(i));
      
    // If all characters are same
    // Size of set will always be 1
    if (s1.size() == 1)
        System.out.println("YES");
    else
        System.out.println("NO");
}
 
// Driver Code
public static void main(String[] args)
{
    String str = "nnnn";
     
    allCharactersSame(str);
}
}
 
// This code is contributed by divyeshrabadiya07


Python3
# Python3 program for
# the above approach
 
# Function to check is
# all the characters in
# string are or not
def allCharactersSame(s):
   
    s1 = []
 
    # Insert characters in
    # the set
    for i in range(len(s)):
        s1.append(s[i])
 
    # If all characters are same
    # Size of set will always be 1
    s1 = list(set(s1))
    if(len(s1) == 1):
        print("YES")
    else:
        print("NO")
 
# Driver code
Str = "nnnn"
allCharactersSame(Str)
 
# This code is contributed by avanitrachhadiya2155


C#
// C# program for above approach
using System;
using System.Collections.Generic;
 
class GFG{
     
// Function to check is all the
// characters in string are or not
static void allCharactersSame(string s)
{
    HashSet s1 = new HashSet();
      
    // Insert characters in the set
    for(int i = 0; i < s.Length; i++)
        s1.Add(s[i]);
       
    // If all characters are same
    // Size of set will always be 1
    if (s1.Count == 1)
        Console.WriteLine("YES");
    else
        Console.WriteLine("NO");
}
 
// Driver code 
static void Main()
{
    string str = "nnnn";
     
    allCharactersSame(str);
}
}
 
// This code is contributed by divyesh072019


Javascript


输出
Yes

快速方法(不是明智的时间复杂度,而是在代码行数方面)

这个想法是在C++ STL中使用find_first_not_of()。
find_first_not_of()查找并返回与指定字符(或任何指定字符,如果是字符串 )不匹配的第一个字符的位置。

C++

// A quick C++ program to find whether the
// string has all same characters or not.
#include 
using namespace std;
 
bool allCharactersSame(string s)
{
    return (s.find_first_not_of(s[0]) == string::npos);
}
 
// Driver code
int main()
{
    string s = "aaa";
    if (allCharactersSame(s))
        cout << "Yes";
    else
        cout << "No";
 
    return 0;
}
输出
Yes

另一种方法是使用SET

这个想法是将字符串的所有字符添加到集合中。添加后,如果集合的大小大于1,则表示存在不同的字符;如果大小恰好为1,则表示仅存在一个唯一字符。

以下是上述逻辑的实现。

C++

// C++ program for above approach
#include 
using namespace std;
 
// Function to check is all the
// characters in string are or not
void allCharactersSame(string s)
{
    set  s1;
   
    // Insert characters in the set
    for ( int i=0 ; i < s.length() ; i++)
        s1.insert(s[i]);
     
    // If all characters are same
    // Size of set will always be 1
    if ( s1.size() == 1 )
        cout << "YES";
    else
        cout << "NO";
}
 
// Driver code
int main()
{
    string str = "nnnn";
    allCharactersSame(str);
      return 0;
}

Java

// Java program for above approach
import java.io.*;
import java.util.*;
 
class GFG{
     
// Function to check is all the
// characters in string are or not
public static void allCharactersSame(String s)
{
    Set s1 = new HashSet();
     
    // Insert characters in the set
    for(int i = 0; i < s.length(); i++)
        s1.add(s.charAt(i));
      
    // If all characters are same
    // Size of set will always be 1
    if (s1.size() == 1)
        System.out.println("YES");
    else
        System.out.println("NO");
}
 
// Driver Code
public static void main(String[] args)
{
    String str = "nnnn";
     
    allCharactersSame(str);
}
}
 
// This code is contributed by divyeshrabadiya07

Python3

# Python3 program for
# the above approach
 
# Function to check is
# all the characters in
# string are or not
def allCharactersSame(s):
   
    s1 = []
 
    # Insert characters in
    # the set
    for i in range(len(s)):
        s1.append(s[i])
 
    # If all characters are same
    # Size of set will always be 1
    s1 = list(set(s1))
    if(len(s1) == 1):
        print("YES")
    else:
        print("NO")
 
# Driver code
Str = "nnnn"
allCharactersSame(Str)
 
# This code is contributed by avanitrachhadiya2155

C#

// C# program for above approach
using System;
using System.Collections.Generic;
 
class GFG{
     
// Function to check is all the
// characters in string are or not
static void allCharactersSame(string s)
{
    HashSet s1 = new HashSet();
      
    // Insert characters in the set
    for(int i = 0; i < s.Length; i++)
        s1.Add(s[i]);
       
    // If all characters are same
    // Size of set will always be 1
    if (s1.Count == 1)
        Console.WriteLine("YES");
    else
        Console.WriteLine("NO");
}
 
// Driver code 
static void Main()
{
    string str = "nnnn";
     
    allCharactersSame(str);
}
}
 
// This code is contributed by divyesh072019

Java脚本


输出
YES

时间复杂度: O(nLogn)

要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”