Funny string

Published on August 06, 2021
Last updated August 06, 2021

Given problem statment

In this challenge, you will 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. abc —> cba 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 give string is funny. If it is, print Funny, otherwise print Not Funny.

solution in java

import java.util.*;

public class Solution {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int num_of_test_cases = sc.nextInt();
        while (num_of_test_cases > 0) {
            String s = sc.next();
            StringBuilder sb = new StringBuilder();
            boolean isValid = false;
            int[] diff_list = new int[s.length() - 1];
            int[] rev_diff_list = new int[s.length() - 1];
            sb.append(s);
            sb.reverse();
            String reverse_s = sb.toString();

            for (int i = 1; i < s.length(); i++) {
                diff_list[i - 1] = Math.abs(s.charAt(i) - s.charAt(i - 1));
                rev_diff_list[i - 1] = Math.abs(reverse_s.charAt(i) - reverse_s.charAt(i - 1));
            }
            isValid = Arrays.equals(diff_list, rev_diff_list);
            String result = isValid ? "Funny" : "Not Funny";
            System.out.println(result);
            num_of_test_cases--;
        }
        sc.close();
    }
}


Tags :