Advertisement
meta1211

Untitled

Aug 13th, 2018
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.86 KB | None | 0 0
  1. //LongestWordFinder.h
  2. #pragma once
  3.  
  4. struct LongestWordData
  5. {
  6. public:
  7.     int StartIndex;
  8.     int Length;
  9.  
  10.     LongestWordData(int startIndex, int length)
  11.     {
  12.         StartIndex = startIndex;
  13.         Length = length;
  14.     }
  15. };
  16.  
  17. LongestWordData FindLongestWord(char* text, int len);
  18.  
  19. char* InvertWord(char* word, int len);
  20.  
  21. char* GetLongestWord(char* text, int len);
  22.  
  23.  
  24. //LongestWordFinder.cpp
  25. #include "LongestWordFinder.h"
  26.  
  27. LongestWordData FindLongestWord(char *text, int len)
  28. {
  29.     int maxLen = 0;
  30.     int curLen = 0;
  31.     int longesWordIndex = 0;
  32.     int curIndex = 0;
  33.  
  34.     while (curIndex < len)
  35.     {
  36.         if (text[curIndex] >= '0' && text[curIndex] <= '9')
  37.         {
  38.             if (curLen > maxLen)
  39.             {
  40.                 maxLen = curLen;
  41.                 longesWordIndex = curIndex - curLen;
  42.             }
  43.             curLen = 0;
  44.         }
  45.         else
  46.         {
  47.             curLen++;
  48.         }
  49.         curIndex++;
  50.     }
  51.     if (curLen > maxLen)
  52.     {
  53.         maxLen = curLen;
  54.         longesWordIndex = curIndex - curLen;
  55.     }
  56.     return LongestWordData(longesWordIndex, maxLen);
  57. }
  58.  
  59. char *InvertWord(char *word, int len)
  60. {
  61.     char *result = new char[len + 1];
  62.     for (int i = 0, k = len - 1; i <= len / 2; i++, k--)
  63.     {
  64.         result[i] = word[k];
  65.         result[k] = word[i];
  66.     }
  67.     result[len] = '\0';
  68.     return result;
  69. }
  70.  
  71. char *GetLongestWord(char *text, int len)
  72. {
  73.     auto longestWordData = FindLongestWord(text, len);
  74.     int wordLen = longestWordData.Length;
  75.     int startIndex = longestWordData.StartIndex;
  76.     char* longestWord = new char[wordLen + 1];
  77.     bool isPalindrome = true;
  78.     for (int i = 0, k = wordLen - 1; i <= wordLen/2; i++, k--)
  79.     {
  80.         longestWord[i] = text[startIndex + i];
  81.         longestWord[k] = text[startIndex + k];
  82.         if (isPalindrome && longestWord[i] != longestWord[k])
  83.         {
  84.             isPalindrome = false;
  85.         }
  86.     }
  87.     longestWord[wordLen] = '\0';
  88.     if (isPalindrome)
  89.     {
  90.         return longestWord;
  91.     }
  92.     else
  93.     {
  94.         char *result = InvertWord(longestWord, wordLen);
  95.         delete longestWord;
  96.         return result;
  97.     }
  98. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement