Find Common Prefix of Strings

Determine prefix from a set of (similar) strings

Never rewrite what is provided to you: os.path.commonprefix does exactly this:

Return the longest path prefix (taken
character-by-character) that is a prefix of all paths in list. If list
is empty, return the empty string (''). Note that this may return
invalid paths because it works a character at a time.

For comparison to the other answers, here's the code:

# Return the longest prefix of all list elements.
def commonprefix(m):
"Given a list of pathnames, returns the longest common leading component"
if not m: return ''
s1 = min(m)
s2 = max(m)
for i, c in enumerate(s1):
if c != s2[i]:
return s1[:i]
return s1

Longest Common Prefix in Javascript

As the longest common prefix must occur in every string of the array you can jus iterate over the length and check if all words have the same char at that index until you find a difference

function prefix(words){
// check border cases size 1 array and empty first word)
if (!words[0] || words.length == 1) return words[0] || "";
let i = 0;
// while all words have the same character at position i, increment i
while(words[0][i] && words.every(w => w[i] === words[0][i]))
i++;

// prefix is the substring from the beginning to the last successfully checked i
return words[0].substr(0, i);
}

console.log(1, prefix([]));
console.log(2, prefix([""]));
console.log(3, prefix(["abc"]));
console.log(4, prefix(["abcdefgh", "abcde", "abe"]));
console.log(5, prefix(["abc", "abc", "abc"]));
console.log(6, prefix(["abc", "abcde", "xyz"]));

How to get common prefix of strings in a list

Use os.path.commonprefix it will do exactly what you want.

In [1]: list = ['nomad', 'normal', 'nonstop', 'noob']

In [2]: import os.path as p

In [3]: p.commonprefix(list)
Out[3]: 'no'

As an aside, naming a list "list" will make it impossible to access the list class, so I would recommend using a different variable name.

Find the common prefix of two strings in idiomatic Swift

This is a recursive functional solution that uses simple array operations upon characters. I think this is the one liner you were looking for.

extension String {
func sharedPrefix(with other: String) -> String {
return characters.isEmpty || other.characters.isEmpty ? "" : (characters.first! != other.characters.first! ? "" : "\(characters.first!)" + String(Array(characters.dropFirst())).sharedPrefix(with: String(Array(other.characters.dropFirst()))))
}
}

Edit (by OP) which could be further boiled down to this, in the interests of readability, although admittedly no longer a true one-liner:

extension String {
func sharedPrefix(with other: String) -> String {
return (self.isEmpty || other.isEmpty || self.first! != other.first!) ? "" :
"\(self.first!)" + String(Array(self.dropFirst())).sharedPrefix(with: String(Array(other.dropFirst())))
}
}

C: print the longest common prefix

This declaration

char found[10] = { '\0' }; 

is redundant and does not make a sense.

Also the function findprefix should return the length of the common prefix.

The function should be declared and defined the following way

size_t findprefix( const char *str1, const char *str2 )
{
size_t n = 0;

for ( ; *str1 && *str1 == *str2; ++str1, ++str2 )
{
++n;
}

return n;
}

And in main you can write

size_t n = findprefix( str1, str2 );

if ( n != 0 ) printf( "%.*s\n", ( int )n, str1 );

Here is a demonstration progarn.

#include <stdio.h>

size_t findprefix( const char *str1, const char *str2 )
{
size_t n = 0;

for ( ; *str1 && *str1 == *str2; ++str1, ++str2 )
{
++n;
}

return n;
}

int main( void )
{
const char *str1 = "Hello Word!";
const char *str2 = "Hello Kallum Smith";

size_t n = findprefix( str1, str2 );

if ( n != 0 ) printf( "\"%.*s\"\n", ( int )n, str1 );

return 0;
}

The program output is

"Hello "

Using the return value of the function you also can dynamically allocate an array or declare a variable length array where you can copy the prefix if it is required.

get common prefix of two string

Here is the non-linq version which is more efficient, clear and readable

public static string CommonPrefix(string a, string b)
{
if (a == null)
throw new ArgumentNullException(nameof(a));

if (b == null)
throw new ArgumentNullException(nameof(b));

var min = Math.Min(a.Length, b.Length);
var sb = new StringBuilder(min);
for (int i = 0; i < min && a[i] == b[i]; i++)
sb.Append(a[i]);

return sb.ToString();
}

use it like

Console.WriteLine(CommonPrefix("TestasdOne", "TestasdTwo")); //Testasd

Longest Common Prefix in String Array in Java

The error in your code is in the part you used without checking that the variable (K) might be larger than the string length (j) of the array.
To solve this problem, it is enough to add a conditional statement before using the variable (K).
Good luck



Related Topics



Leave a reply



Submit