Longest Happy Prefix LeetCode solution in C++
1class Solution {2public:3string longestPrefix(string s) {4if (s == "") return "";5int n = s.length();6int arr[n];7fill(arr, arr + n, 0);8int prevLPS = 0, i = 1;9while (i < n) {10if (s[i] == s[prevLPS]) {11arr[i] = prevLPS + 1;12i++;13prevLPS++;14} else if (prevLPS == 0) {15arr[i] = 0;16i++;17} else {18prevLPS = arr[prevLPS - 1];19}20}21int oplen = arr[n - 1];22string temp = s.substr(n - oplen, oplen);23return temp;24}25};