mirror of
https://github.com/TheAlgorithms/Java.git
synced 2025-07-06 17:29:31 +08:00
refactor: CharactersSame
(#5396)
This commit is contained in:
@ -5,25 +5,19 @@ public final class CharactersSame {
|
||||
}
|
||||
|
||||
/**
|
||||
* Driver Code
|
||||
*/
|
||||
public static void main(String[] args) {
|
||||
assert isAllCharactersSame("");
|
||||
assert !isAllCharactersSame("aab");
|
||||
assert isAllCharactersSame("aaa");
|
||||
assert isAllCharactersSame("11111");
|
||||
}
|
||||
|
||||
/**
|
||||
* check if all the characters of a string are same
|
||||
* Checks if all characters in the string are the same.
|
||||
*
|
||||
* @param s the string to check
|
||||
* @return {@code true} if all characters of a string are same, otherwise
|
||||
* {@code false}
|
||||
* @return {@code true} if all characters in the string are the same or if the string is empty, otherwise {@code false}
|
||||
*/
|
||||
public static boolean isAllCharactersSame(String s) {
|
||||
for (int i = 1, length = s.length(); i < length; ++i) {
|
||||
if (s.charAt(i) != s.charAt(0)) {
|
||||
if (s.isEmpty()) {
|
||||
return true; // Empty strings can be considered as having "all the same characters"
|
||||
}
|
||||
|
||||
char firstChar = s.charAt(0);
|
||||
for (int i = 1; i < s.length(); i++) {
|
||||
if (s.charAt(i) != firstChar) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user