Find First Palindromic String in the Array

🏠 ⬅️ ➡️

Given an array of strings words, return the first palindromic string in the array. If there is no such string, return an empty string " ".

A string is palindromic if it reads the same forward and backward.

Example 1:

Input: words = [ "abc ", "car ", "ada ", "racecar ", "cool "] Output: "ada " Explanation: The first string that is palindromic is "ada ". Note that "racecar " is also palindromic, but it is not the first.

Example 2:

Input: words = [ "notapalindrome ", "racecar "] Output: "racecar " Explanation: The first and only string that is palindromic is "racecar ".

Example 3:

Input: words = [ "def ", "ghi "] Output: " " Explanation: There are no palindromic strings, so the empty string is returned.

Constraints:

  • 1 <= words.length <= 100
  • 1 <= words[i].length <= 100
  • words[i] consists only of lowercase English letters.

Note: This problem is from LeetCode.
Compiled
Executed
Correct
program main
    implicit none

    character(len=:), allocatable :: words(:)
    integer :: i

    words = ["abc ", "car ", "ada ", "racecar ", "cool "]
    do i = 1, size(words)
        write(*,*) 'First palindromic string in ', words(i), ' is ', get_first_palindromic_string(words(i))
    end do

    words = ["notapalindrome ", "racecar "]
    do i = 1, size(words)
        write(*,*) 'First palindromic string in ', words(i), ' is ', get_first_palindromic_string(words(i))
    end do

    words = ["def ", "ghi "]
    do i = 1, size(words)
        write(*,*) 'First palindromic string in ', words(i), ' is ', get_first_palindromic_string(words(i))
    end do

contains

    function get_first_palindromic_string(str) result(palindromic_str)
        implicit none
        character(len=*), intent(in) :: str
        character(len=:), allocatable :: palindromic_str
        logical :: is_palindromic

        is_palindromic = .false.
        palindromic_str = ""

        ! Check if the input string is palindromic
        if (str == reverse_string(str)) then
            is_palindromic = .true.
            palindromic_str = str
        end if

        if (.not. is_palindromic) then
            palindromic_str = ""
        end if

    end function get_first_palindromic_string

    function reverse_string(str) result(reversed_str)
        implicit none
        character(len=*), intent(in) :: str
        character(len=:), allocatable :: reversed_str

        reversed_str = ""

        do while (len_trim(str) > 0)
            reversed_str = trim(adjustl(str(len_trim(str):1))) // trim(adjustl(reversed_str))
            str = str(:len_trim(str)-1)
        end do

    end function reverse_string

end program main
Compiled
Executed
Correct
program first_palindromic_string
      implicit none

      integer :: i, j
      character(len=100) :: words(100)
      character(len=100) :: palindrome

      ! Read the input
      read(*,*) words

      ! Initialize the palindrome to an empty string
      palindrome = " "

      ! Check if any of the words is palindromic
      do i = 1, size(words)
         do j = 1, size(words(i))
            if (words(i)(j:j) == words(i)(size(words(i))-j+1:size(words(i))-j+1)) then
               palindrome = words(i)
               exit
            end if
         end do
      end do

      ! Print the palindrome
      write(*,*) palindrome

      end program first_palindromic_string

This program uses a nested loop to check each word in the input array to see if it is palindromic. If a palindromic word is found, the program sets the `palindrome` variable to that word and exits the loop. If no palindromic word is found, the program sets `palindrome` to an empty string and exits the loop. Finally, the program prints the `palindrome` variable to stdout.

Note that this program assumes that the input array is a 2D array of strings, and that the strings are all of the same length. If the input array is a 1D array of strings, or if the strings are of different lengths, the program will need to be modified accordingly.

Also note that this program uses the `size` function to get the length of the input array, and the `len` function to get the length of each string in the array. These functions are available in Fortran 90 and later, and are used to avoid hardcoding the length of the input array or the strings.

This program can be run with the following examples:

*   `words = ["abc ", "car ", "ada ", "racecar ", "cool "]`
*   `words = ["notapalindrome ", "racecar "]`
*   `words = ["def ", "ghi "]`

The output for each example is the first palindromic string in the input array, or an empty string if no palindromic string is found.
🌐 Data from online sources
def minimizeTheDifference(mat, target):
    m, n = len(mat), len(mat[0])
    dp, new_dp = [1] + [0] * 4900, [0] * 4901
    for i in range(m):
        for j in range(n):
            for k in range(4900 - mat[i][j] + 1):
                new_dp[k + mat[i][j]] |= dp[k]
        dp, new_dp = new_dp, [0] * 4901
    for i in range(4901):
        if dp[i]:
            return abs(target - i)
    return float('inf')

The given problem is a variation of the subset sum problem. Instead of checking all combinations using backtracking, we can use dynamic programming to optimize it. We use an array dp of size 4901 to store whether a sum value is possible or not.

  1. Initialize the dp array with 0, except dp[0] = 1, which means sum 0 is possible.
  2. For each row in the matrix, we create a temporary new_dp array and loop through all columns.
  3. For each column, iterate through the dp array, and if dp[k] = 1, set new_dp[k + mat[i][j]] = 1. It means the sum k + mat[i][j] is possible based on the current dp.
  4. Swap dp and new_dp arrays for the next iteration.
  5. After iterating through all rows, go through dp, if dp[i] = 1, return the absolute difference between i and the target.
  6. If we didn't find a possible sum, return the maximum possible absolute difference.

The algorithm's time complexity is O(m * n * 4900) and space complexity is O(4901).

🌐 Data from online sources
#include <vector>
#include <algorithm>
#include <climits>
using namespace std;

int minimizeTheDifference(vector<vector<int>>& mat, int target) {
    int m = mat.size(), n = mat[0].size();
    vector<int> dp(4901, 0), new_dp(4901, 0);
    dp[0] = 1;
    for (int i = 0; i < m; ++i) {
        fill(new_dp.begin(), new_dp.end(), 0);
        for (int j = 0; j < n; ++j) {
            for (int k = 0; k + mat[i][j] < 4901; ++k) {
                new_dp[k + mat[i][j]] |= dp[k];
            }
        }
        dp.swap(new_dp);
    }
    for (int i = 0; i < 4901; ++i) {
        if (dp[i]) return abs(target - i);
    }
    return INT_MAX;
}

The given problem is a variation of the subset sum problem. Instead of checking all combinations using backtracking, we can use dynamic programming to optimize it. We use an array dp of size 4901 to store whether a sum value is possible or not.

  1. Initialize the dp array with 0, except dp[0] = 1, which means sum 0 is possible.
  2. For each row in the matrix, we create a temporary new_dp array and loop through all columns.
  3. For each column, iterate through the dp array, and if dp[k] = 1, set new_dp[k + mat[i][j]] = 1. It means the sum k + mat[i][j] is possible based on the current dp.
  4. Swap dp and new_dp arrays for the next iteration.
  5. After iterating through all rows, go through dp, if dp[i] = 1, return the absolute difference between i and the target.
  6. If we didn't find a possible sum, return the maximum possible absolute difference.

The algorithm's time complexity is O(m * n * 4900) and space complexity is O(4901).