Funny String

Determine whether a string is funny or not. 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.

Determine whether a given string is funny. If it is, return Funny, otherwise, return Not Funny. 

Example:

Input:  s="acxz"
Output: Funny

Approach

Java


public class FunnyString {
    public static void main(String[] args) {
        String s = "acxz";
        String result = funnyString(s);
        System.out.println(result);
    }

    static String funnyString(String s) {
        String s2 = "";
        for (int i = s.length() - 1; i >= 0; i--) {
            s2 += s.charAt(i);
        }
        for (int i = 0; i < s.length() - 1; i++) {
            if (Math.abs(s.charAt(i) - s.charAt(i + 1)) != 
                Math.abs(s2.charAt(i) - s2.charAt(i + 1)))
                return "Not Funny";
        }
        return "Funny";
    }

}

C++

#include <bits/stdc++.h>
using namespace std;

string funnyString(string s)
{
    vector<intres;
    string s2 = "";
    for (int i = s.size() - 1i >= 0i--)
        s2 += s[i];
    for (int i = 0i < s.size() - 1i++)
    {
        if (abs(s[i] - s[i + 1]) != abs(s2[i] - s2[i + 1]))
            return "Not Funny";
    }
    return "Funny";
}

int main()
{

    string s = "acxz";
    string result = funnyString(s);

    cout << result << "\n";

    return 0;
}


No comments:

Post a Comment