Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //LongestWordFinder.h
- #pragma once
- struct LongestWordData
- {
- public:
- int StartIndex;
- int Length;
- LongestWordData(int startIndex, int length)
- {
- StartIndex = startIndex;
- Length = length;
- }
- };
- LongestWordData FindLongestWord(char* text, int len);
- char* InvertWord(char* word, int len);
- char* GetLongestWord(char* text, int len);
- //LongestWordFinder.cpp
- #include "LongestWordFinder.h"
- LongestWordData FindLongestWord(char *text, int len)
- {
- int maxLen = 0;
- int curLen = 0;
- int longesWordIndex = 0;
- int curIndex = 0;
- while (curIndex < len)
- {
- if (text[curIndex] >= '0' && text[curIndex] <= '9')
- {
- if (curLen > maxLen)
- {
- maxLen = curLen;
- longesWordIndex = curIndex - curLen;
- }
- curLen = 0;
- }
- else
- {
- curLen++;
- }
- curIndex++;
- }
- if (curLen > maxLen)
- {
- maxLen = curLen;
- longesWordIndex = curIndex - curLen;
- }
- return LongestWordData(longesWordIndex, maxLen);
- }
- char *InvertWord(char *word, int len)
- {
- char *result = new char[len + 1];
- for (int i = 0, k = len - 1; i <= len / 2; i++, k--)
- {
- result[i] = word[k];
- result[k] = word[i];
- }
- result[len] = '\0';
- return result;
- }
- char *GetLongestWord(char *text, int len)
- {
- auto longestWordData = FindLongestWord(text, len);
- int wordLen = longestWordData.Length;
- int startIndex = longestWordData.StartIndex;
- char* longestWord = new char[wordLen + 1];
- bool isPalindrome = true;
- for (int i = 0, k = wordLen - 1; i <= wordLen/2; i++, k--)
- {
- longestWord[i] = text[startIndex + i];
- longestWord[k] = text[startIndex + k];
- if (isPalindrome && longestWord[i] != longestWord[k])
- {
- isPalindrome = false;
- }
- }
- longestWord[wordLen] = '\0';
- if (isPalindrome)
- {
- return longestWord;
- }
- else
- {
- char *result = InvertWord(longestWord, wordLen);
- delete longestWord;
- return result;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement