Last active
April 14, 2022 02:57
-
-
Save MrDave1999/82d7a0b0c0950a36fcc40f2470a4e4da to your computer and use it in GitHub Desktop.
Longest Common Prefix
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
https://leetcode.com/problems/longest-common-prefix/ | |
Write a function to find the longest common prefix string amongst an array of strings. | |
If there is no common prefix, return an empty string "". | |
Example 1: | |
Input: strs = ["flower","flow","flight"] | |
Output: "fl" | |
Example 2: | |
Input: strs = ["dog","racecar","car"] | |
Output: "" | |
Explanation: There is no common prefix among the input strings. | |
Constraints: | |
1 <= strs.length <= 200 | |
0 <= strs[i].length <= 200 | |
strs[i] consists of only lower-case English letters. | |
*/ | |
using System; | |
class Program | |
{ | |
public static string LongestCommonPrefix(params string[] words) | |
{ | |
var firstWord = words[0]; | |
string commonPrefix = ""; | |
int arrayLength = words.Length; | |
for(int i = 0, len = firstWord.Length; i < len; ++i) | |
{ | |
var prefixToCompare = firstWord.Substring(0, i + 1); | |
for(int j = 1; j < arrayLength; ++j) | |
{ | |
if(words[j].IndexOf(prefixToCompare) == -1) | |
return commonPrefix; | |
} | |
commonPrefix = prefixToCompare; | |
} | |
return commonPrefix; | |
} | |
public static void PrintResult(params string[] strs) | |
{ | |
var result = LongestCommonPrefix(strs); | |
if(result.Length == 0) | |
Console.WriteLine("There is no common prefix among the input strings."); | |
else | |
Console.WriteLine($"Common Prefix: {result}"); | |
} | |
static void Main() | |
{ | |
PrintResult("flower","flow","flight"); | |
PrintResult("dog","racecar","car"); | |
PrintResult("mom", "mom", "mom", "mom"); | |
PrintResult("motherfuck", "mom", "mom", "mom"); | |
PrintResult("motherfuck", "body", "mom", "mom"); | |
PrintResult("motherfuck", "mom", "body", "mom"); | |
PrintResult("leets", "leetcode", "leet", "leeds"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment