Longest Common Prefix

Longest Common Prefix LeetCode Problem

Create a function to find the longest common prefix from an array of strings.

Return the longest common prefix from the strings, if there is no common prefix return “”.

Longest_Common_Prefix <- function(strs){
x <- strsplit(strs, "")

# find the smallest word for loop iteration

y <- lapply(x, length)

imax <- min(unlist(y))

Current_Prefix = ""

Prefix = ""

for(i in 1:imax){
  
Current_Prefix <-  substr(strs[1], start = 1, stop = i)
  
  if(all(startsWith(strs, Current_Prefix))) {
  
  Prefix <- Current_Prefix
 
 }
}
Prefix
}
> Longest_Common_Prefix(strs=c("flower", "flow", "flight"))
[1] "fl"

> Longest_Common_Prefix(strs = c("dog","racecar","car"))
[1] ""

Leave a Reply

Your email address will not be published. Required fields are marked *