반응형

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#region Question 1.5 | |
/// <summary> | |
/// 같은 문자가 연속으로 반복될 경우, 그 횟수를 사용해 문자열을 압축하라. | |
/// 만약, 압축할 수 없다면 원래 문자열을 반환하라. | |
/// </summary> | |
/// <param name="input">입력 문자열</param> | |
/// <returns><paramref name="input"/>이 압축된 문자열</returns> | |
public static string Q5_Compress(string input) | |
{ | |
System.Text.StringBuilder sb = new System.Text.StringBuilder(); | |
char check = input[0]; | |
int count = 1; | |
bool compare = false; | |
for(int index = 1; index < input.Length; index++) | |
{ | |
if(check == input[index]) | |
{ | |
count++; | |
compare = true; | |
} | |
else | |
{ | |
sb.Append(check); | |
sb.Append(count); | |
check = input[index]; | |
count = 1; | |
} | |
} | |
sb.Append(check); | |
sb.Append(count); | |
if (compare) | |
{ | |
return sb.ToString(); | |
} | |
else | |
{ | |
//압축을 시도한 적이 없으므로, 기존 문자열을 그대로 반환 | |
return input; | |
} | |
} | |
#endregion |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[TestMethod] | |
public void Q1_5() | |
{ | |
Assert.AreEqual(DataStruct.Q5_Compress("abbccccccde"), "a1b2c6d1e1"); | |
} |
반응형
'Develop > 코딩인터뷰' 카테고리의 다른 글
[코딩인터뷰] 문제 1.7 (0) | 2020.04.03 |
---|---|
[코딩인터뷰] 문제 1.6 (0) | 2020.04.03 |
[코딩인터뷰] 문제 1.4 (0) | 2020.04.03 |
[코딩인터뷰] 문제 1.3 (0) | 2020.04.03 |
[코딩인터뷰] 문제 1.2 (0) | 2020.04.03 |
꾸준히 노력하는 개발자 "김예건" 입니다.