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
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 17 additions and 36 deletions

View File

@ -5,25 +5,19 @@ public final class CharactersSame {
} }
/** /**
* Driver Code * Checks if all characters in the string are the same.
*/
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
* *
* @param s the string to check * @param s the string to check
* @return {@code true} if all characters of a string are same, otherwise * @return {@code true} if all characters in the string are the same or if the string is empty, otherwise {@code false}
* {@code false}
*/ */
public static boolean isAllCharactersSame(String s) { public static boolean isAllCharactersSame(String s) {
for (int i = 1, length = s.length(); i < length; ++i) { if (s.isEmpty()) {
if (s.charAt(i) != s.charAt(0)) { 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; return false;
} }
} }

View File

@ -1,28 +1,15 @@
package com.thealgorithms.strings; package com.thealgorithms.strings;
import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
public class CharacterSameTest { class CharactersSameTest {
@Test @ParameterizedTest
public void isAllCharactersSame() { @CsvSource({"aaa, true", "abc, false", "'1 1 1 1', false", "111, true", "'', true", "' ', true", "'. ', false", "'a', true", "' ', true", "'ab', false", "'11111', true", "'ababab', false", "' ', true", "'+++', true"})
String input1 = "aaa"; void testIsAllCharactersSame(String input, boolean expected) {
String input2 = "abc"; assertEquals(CharactersSame.isAllCharactersSame(input), expected);
String input3 = "1 1 1 1";
String input4 = "111";
String input5 = "";
String input6 = " ";
String input7 = ". ";
assertTrue(CharactersSame.isAllCharactersSame(input1));
assertFalse(CharactersSame.isAllCharactersSame(input2));
assertFalse(CharactersSame.isAllCharactersSame(input3));
assertTrue(CharactersSame.isAllCharactersSame(input4));
assertTrue(CharactersSame.isAllCharactersSame(input5));
assertTrue(CharactersSame.isAllCharactersSame(input6));
assertFalse(CharactersSame.isAllCharactersSame(input7));
} }
} }