Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

add StringCompressionTest#43

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Open
namnhse00502x wants to merge1 commit intorampatra:master
base:master
Choose a base branch
Loading
fromnamnhse00502x:master
Open
Changes fromall commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
package com.ctci.arraysandstrings;

import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.*;

class StringCompressionTest {
@Test
void case1() {
String input = "";
String expectedOutput = "";
String actualOutput = compressString(input);
assertEquals(expectedOutput, actualOutput);
}

@Test
void case2() {
String input = "abc";
String expectedOutput = "abc";
String actualOutput = compressString(input);
assertEquals(expectedOutput, actualOutput);
}

@Test
void case3() {
String input = "aaabbccc";
String expectedOutput = "a3b2c3";
String actualOutput = compressString(input);
assertEquals(expectedOutput, actualOutput);
}

@Test
void case4() {
String input = "aaabbbccc";
String expectedOutput = "a3b3c3";
String actualOutput = compressString(input);
assertEquals(expectedOutput, actualOutput);
}

@Test
void case5() {
String input = "abcd";
String expectedOutput = "abcd";
String actualOutput = compressString(input);
assertEquals(expectedOutput, actualOutput);
}


private static String compressString(String str) {
StringBuilder compressedSb = new StringBuilder();
int countConsecutive = 0;
for (int i = 0; i < str.length(); i++) {
countConsecutive++;

/* If next character is different than current, append this char to result. */
if (i + 1 >= str.length() || str.charAt(i) != str.charAt(i + 1)) {
compressedSb.append(str.charAt(i));
compressedSb.append(countConsecutive);
countConsecutive = 0;
}
}
return compressedSb.length() < str.length() ? compressedSb.toString() : str;
}
}

[8]ページ先頭

©2009-2025 Movatter.jp