본문 바로가기

Develop/코딩인터뷰

[코딩인터뷰] 문제 1.5

반응형

코딩 인터뷰
문제 1.5

#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
view raw Code_Q1_5.cs hosted with ❤ by GitHub
[TestMethod]
public void Q1_5()
{
Assert.AreEqual(DataStruct.Q5_Compress("abbccccccde"), "a1b2c6d1e1");
}
view raw Test_Q1_5.cs hosted with ❤ by GitHub
반응형

'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