Advertisement
exmkg

3-1

Jan 14th, 2025
47
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.90 KB | None | 0 0
  1. class Solution {
  2.     public String longestCommonPrefix(String[] strs) {
  3.         if (strs == null || strs.length == 0) {
  4.             return "";
  5.         }
  6.         // Initialize 'prefix' with the longest possible prefix.
  7.         // 'prefix' cannot be longer than any of the strings, so
  8.         // simply initialize it with strs[0].
  9.         String prefix = strs[0];
  10.  
  11.         // Iterate over all strings.
  12.         for (int i = 1; i < strs.length; i++) {
  13.             // Until 'prefix' is not a prefix of the current string,
  14.             // reduce 'prefix' by one character and try to match again.
  15.             while (strs[i].indexOf(prefix) != 0) {
  16.                 // Removing the last character from 'prefix'.
  17.                 prefix = prefix.substring(0, prefix.length() - 1);
  18.             }
  19.         }
  20.         // Return found 'prefix' as it is a prefix of all strings in the list.
  21.         return prefix;
  22.     }
  23. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement