fueanta

Longest Common Prefix in Typescript

Jun 23rd, 2021 (edited)
99
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function longestCommonPrefix(strs: string[]): string {
  2.     if (strs.length === 0) return "";
  3.    
  4.     let prefix = strs[0];
  5.    
  6.     for (let i = 1; i < strs.length; i++) {
  7.         while (strs[i].search(prefix) !== 0) {
  8.             prefix = prefix.substr(0, prefix.length - 1);
  9.             if (prefix.length === 0) return "";
  10.         }
  11.     }
  12.    
  13.     return prefix;
  14. };
RAW Paste Data