refactor: CharactersSame (#5396)

This commit is contained in:
Alex Klymenko
2024-08-26 08:55:50 +02:00
committed by GitHub
parent be6b0d835b
commit 5f6510f0fa
2 changed files with 17 additions and 36 deletions

View File

@ -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;
}
}