Quick way to check if all the characters of a string are same
Given a string, check if all the characters of the string are the same or not.
Examples:
Input : s = “geeks”
Output : No
Input : s = “gggg”
Output : Yes
Simple Way
To find whether a string has all the same characters. Traverse the whole string from index 1 and check whether that character matches the first character of the string or not. If yes, then match until string size. If no, then break the loop.
C++
#include <iostream>
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 ;
}
int main()
{
string s = "aaa" ;
if (allCharactersSame(s))
cout << "Yes" ;
else
cout << "No" ;
return 0;
}
|
Java
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 ;
}
static public void main (String[] args){
String s = "aaa" ;
if (allCharactersSame(s))
System.out.println( "Yes" );
else
System.out.println( "No" );
}
}
|
Python3
def allCharactersSame(s) :
n = len (s)
for i in range ( 1 , n) :
if s[i] ! = s[ 0 ] :
return False
return True
if __name__ = = "__main__" :
s = "aaa"
if allCharactersSame(s) :
print ( "Yes" )
else :
print ( "No" )
|
C#
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 ;
}
static public void Main (String []args){
string s = "aaa" ;
if (allCharactersSame(s))
Console.WriteLine( "Yes" );
else
Console.WriteLine( "No" );
}
}
|
PHP
<?php
function allCharactersSame( $s )
{
$n = strlen ( $s );
for ( $i = 1; $i < $n ; $i ++)
if ( $s [ $i ] != $s [0])
return false;
return true;
}
$s = "aaa" ;
if (allCharactersSame( $s ))
echo "Yes" ;
else
echo "No" ;
?>
|
Javascript
<script>
function allCharactersSame(s)
{
let n = s.length;
for (let i = 1; i < n; i++)
if (s[i] != s[0])
return false ;
return true ;
}
let s = "aaa" ;
if (allCharactersSame(s))
document.write( "Yes" );
else
document.write( "No" );
</script>
|
Time Complexity: O(n), here n is the length of the string.
Auxiliary Space: O(1), as constant extra space is used.
Quick Way (Not time complexity wise, but in terms of number of lines of code)
The idea is to use find_first_not_of() in C++ STL.
find_first_not_of() finds and returns the position of the first character that does not match a specified character (or any of the specified characters in case of a string).
C++
#include <iostream>
using namespace std;
bool allCharactersSame(string s)
{
return (s.find_first_not_of(s[0]) == string::npos);
}
int main()
{
string s = "aaa" ;
if (allCharactersSame(s))
cout << "Yes" ;
else
cout << "No" ;
return 0;
}
|
Java
import java.util.*;
public class Main {
static boolean allCharactersSame(String s) {
for ( int i = 1 ; i < s.length(); i++) {
if (s.charAt(i) != s.charAt( 0 )) {
return false ;
}
}
return true ;
}
public static void main(String[] args) {
String s = "aaa" ;
if (allCharactersSame(s))
System.out.println( "Yes" );
else
System.out.println( "No" );
}
}
|
Python3
def allCharactersSame(s):
return all (c = = s[ 0 ] for c in s)
s = "aaa"
if allCharactersSame(s):
print ( "Yes" )
else :
print ( "No" )
|
C#
using System;
public class GFG {
static bool allCharactersSame( string s)
{
return (s.TrimStart(s[0]) == "" );
}
static public void Main()
{
string s = "aaa" ;
if (allCharactersSame(s))
Console.WriteLine( "Yes" );
else
Console.WriteLine( "No" );
}
}
|
Javascript
function allCharactersSame(s) {
return s.split( '' ).every(c => c === s[0]);
}
const s = "aaa" ;
if (allCharactersSame(s)) {
console.log( "Yes" );
} else {
console.log( "No" );
}
|
Time Complexity: O(N)
Auxiliary Space: O(1)
Quick Way (Not time complexity wise, but in terms of number of lines of code)
The idea is to use built-in function in Python.
The function returns True if all items in an iterable object are same with comparing character, otherwise it returns False. For empty iterable object, the function also returns True.
Python3
s = "aaa"
all_same = all (ch = = s[ 0 ] for ch in s)
print (all_same)
|
Time Complexity: O(N) [For iteration]
Auxiliary Space: O(1)
One other way is using a SET
The idea is to add all the characters of a string to a set. After adding, if the size of the set is greater than 1, it means different characters are present, if the size is exactly 1, it means there is only one unique character.
Below is the implementation of the above logic.
C++
#include <bits/stdc++.h>
using namespace std;
void allCharactersSame(string s)
{
set < char > s1;
for ( int i=0 ; i < s.length() ; i++)
s1.insert(s[i]);
if ( s1.size() == 1 )
cout << "YES" ;
else
cout << "NO" ;
}
int main()
{
string str = "nnnn" ;
allCharactersSame(str);
return 0;
}
|
Java
import java.io.*;
import java.util.*;
class GFG{
public static void allCharactersSame(String s)
{
Set<Character> s1 = new HashSet<Character>();
for ( int i = 0 ; i < s.length(); i++)
s1.add(s.charAt(i));
if (s1.size() == 1 )
System.out.println( "YES" );
else
System.out.println( "NO" );
}
public static void main(String[] args)
{
String str = "nnnn" ;
allCharactersSame(str);
}
}
|
Python3
def allCharactersSame(s):
s1 = []
for i in range ( len (s)):
s1.append(s[i])
s1 = list ( set (s1))
if ( len (s1) = = 1 ):
print ( "YES" )
else :
print ( "NO" )
Str = "nnnn"
allCharactersSame( Str )
|
C#
using System;
using System.Collections.Generic;
class GFG{
static void allCharactersSame( string s)
{
HashSet< char > s1 = new HashSet< char >();
for ( int i = 0; i < s.Length; i++)
s1.Add(s[i]);
if (s1.Count == 1)
Console.WriteLine( "YES" );
else
Console.WriteLine( "NO" );
}
static void Main()
{
string str = "nnnn" ;
allCharactersSame(str);
}
}
|
Javascript
<script>
function allCharactersSame(s)
{
let s1 = new Set();
for (let i = 0; i < s.length; i++)
{
s1.add(s[i]);
}
if (s1.size == 1)
document.write( "YES" );
else
document.write( "NO" );
}
let str = "nnnn" ;
allCharactersSame(str);
</script>
|
Time Complexity: O(nLogn), As insertion in a set takes Logn time and we are inserting n elements.
Auxiliary Space: O(n), Extra space is used to store the elements in the set.
Last Updated :
23 Mar, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...