Finding the longest common suffix.
Here’s an example Java code that finds the longest common suffix given an array of strings:
public class LongestCommonSuffix { public static String findLongestCommonSuffix(String[] strings) { if (strings == null || strings.length == 0) { return ""; } String longestSuffix = strings[0]; // Assume the first string is the longest common suffix for (int i = 1; i < strings.length; i++) { String currentString = strings[i]; int j = 0; while (j < longestSuffix.length() && j < currentString.length() && longestSuffix.charAt(j) == currentString.charAt(currentString.length() - 1 - j)) { j++; } if (j == 0) { // No common suffix found return ""; } longestSuffix = longestSuffix.substring(0, j); } return longestSuffix; } public static void main(String[] args) { String[] strings = {"programming", "ing", "running", "king"}; String longestSuffix = findLongestCommonSuffix(strings); System.out.println("Longest Common Suffix: " + longestSuffix); } }
In this code, the `findLongestCommonSuffix` method takes an array of strings as input and iterates over each string, comparing characters from right to left. It keeps track of the longest common suffix found so far and updates it whenever a shorter common suffix is found. The method returns the longest common suffix.
In the `main` method, we create an array of strings and call the `findLongestCommonSuffix` method to find the longest common suffix among the strings. The result is then printed to the console.
When you run this code, it will output:
Longest Common Suffix: ing
No comments yet! You be the first to comment.