Medium

Given a string, return its encoding defined as follows:

  • First, the string is divided into the least possible number of disjoint substrings consisting of identical characters
    • for example, "aabbbc" is divided into ["aa", "bbb", "c"]
  • Next, each substring with length greater than one is replaced with a concatenation of its length and the repeating character
    • for example, substring "bbb" is replaced by "3b"
  • Finally, all the new strings are concatenated together in the same order and a new string is returned.

Example

For s = "aabbbc", the output should be
lineEncoding(s) = "2a3bc".

Input/Output

  • [execution time limit] 0.5 seconds (c)

  • [input] string s

    String consisting of lowercase English letters.

    Guaranteed constraints:
    4 ≤ s.length ≤ 15.

  • [output] string

    • Encoded version of s.

[C] Syntax Tips

// Prints help message to the console
// Returns a string
char * helloWorld(char * name) {
    char * answer = malloc(strlen(name) + 8);
    printf("This prints to the console when you Run Tests");
    strcpy(answer, "Hello, ");
    strcat(answer, name);
    return answer;
}

더보기

Solution

char *lineEncoding(char *s)
{
	int count=0, current=0;
	char *encoding=(char *)calloc((strlen(s)+1),sizeof(char));

	for(int i=0;i<strlen(s);i++,count++)
	{
		if(strlen(s)==1)
			return s;

		if(i==0)
			continue;

		if(s[i]!=s[i-1] || i==strlen(s)-1)
		{
			if(s[i]!=s[i-1] && i==strlen(s)-1)
			{
				if(count==1)
					encoding[current++]=s[i-1];
				else
				{
					if(count>9)
						encoding[current++]='0'+(count/10);
					encoding[current++]='0'+(count%10);
					encoding[current++]=s[i-1];
				}

				encoding[current++]=s[i];
			}
			else if(i==strlen(s)-1)
			{
				count++;

				if(count>9)
					encoding[current++]='0'+(count/10);
				encoding[current++]='0'+(count%10);
				encoding[current++]=s[i];
			}
			else
			{
				if(count==1)
					encoding[current++]=s[i-1];
				else
				{
					if(count>9)
						encoding[current++]='0'+(count/10);
					encoding[current++]='0'+(count%10);
					encoding[current++]=s[i-1];
				}
				count=0;
			}
		}
	}

	return encoding;
}
728x90

'Codesignal' 카테고리의 다른 글

<Codesignal> deleteDigit  (0) 2020.04.06
<Codesignal> chessKnight  (0) 2020.04.06
<Codesignal> isDigit  (0) 2020.04.06
<Codesignal> Is MAC48 Address?  (0) 2020.04.06
<Codesignal> Elections Winners  (0) 2020.04.06

+ Recent posts