Easy

Define a word as a sequence of consecutive English letters. Find the longest word from the given string.

Example

For text = "Ready, steady, go!", the output should be
longestWord(text) = "steady".

Input/Output

  • [execution time limit] 0.5 seconds (c)

  • [input] string text

    Guaranteed constraints:
    4 ≤ text.length ≤ 50.

  • [output] string

    • The longest word from text. It's guaranteed that there is a unique output.

[C] Syntax Tips

// Prints help messa

// 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 *longestWord(char *text)
{
	int maxCount=0;

	for(int i=0;i<strlen(text);i++)
	{
		int start;

		if((i==0&&isalpha(text[i])) || (!isalpha(text[i-1])&&isalpha(text[i])))
		{
			start=i;
			while(isalpha(text[i])&&i<strlen(text))
				i++;

			maxCount=i-1-start>maxCount?i-1-start:maxCount;
		}
	}

	for(int i=0;i<strlen(text);i++)
	{
		int start;

		if((i==0&&isalpha(text[i])) || (!isalpha(text[i-1])&&isalpha(text[i])))
		{
			start=i;
			while(isalpha(text[i])&&i<strlen(text))
				i++;

			if(i-1-start==maxCount)
			{
				for(int j=0;j<=maxCount;j++)
					text[j]=text[j+start];
				text[maxCount+1]='\0';

				return text;
			}
		}
	}
}
728x90

'Codesignal' 카테고리의 다른 글

<Codesignal> sumUpNumbers  (0) 2020.04.06
<Codesignal> Valid Time  (0) 2020.04.06
<Codesignal> deleteDigit  (0) 2020.04.06
<Codesignal> chessKnight  (0) 2020.04.06
<Codesignal> lineEncoding  (0) 2020.04.06

+ Recent posts