The idea is this: To determine whether a string is funny, create a copy of the string in reverse e.g. . Iterating through each string, compare the absolute difference in the ascii values of the characters at positions 0 and 1, 1 and 2 and so on to the end. If the list of absolute differences is the same for both strings, they are funny.
This is my Python code for the same:
def funnyString(s):
temp = s[::-1]
arr1,arr2 = [],[]
for i in range(len(s)-1):
arr1.append(abs(ord(s[i+1])-ord(s[i])))
arr2.append(abs(ord(temp[i+1])-ord(temp[i])))
if arr1 == arr2: return "Funny"
else: return "Not Funny"
It works but I want to get some feedback if this is too verbose and should/can be shortened. One solution example:
acxz
bcxz
Funny
Not Funny
The same implementation in C++
string funnyString(string s) {
string temp;
temp = s;
vector<int> arr1, arr2;
reverse(temp.begin(), temp.end());
for (int i = 0; i < s.length()-1; i++) {
arr1.push_back(fabs(int(s[i + 1]) - int(s[i])));
arr2.push_back(fabs(int(temp[i + 1]) - int(temp[i])));
}
if (arr1 == arr2) return "Funny";
else return "Not Funny";
}