0

I'm trying to make a function as this:

  • input: some strings (example: "thisis_a_string123", "thisis_a_nother_string123", "thisis_not_a_string123")
  • ouput: a longest substring counted from the 1st character (example: "thisis_"), if not found, return an empty string: "".

Since the output is only: "thisis_", not a Longest Common Subsequence like this: "thisis_a_string123", so it is different with: https://rosettacode.org/wiki/Longest_common_subsequence

and this: Getting the longest common subsequence in ERLANG

any help will be appreciated, thank you !!

Cœur
  • 37,241
  • 25
  • 195
  • 267
zoro
  • 333
  • 3
  • 13

2 Answers2

2

From what I understand, you want the longest common prefix, not substring. This can be done by first defining a function that works with 2 lists:

lcp([X | XS], [X | YS]) ->
  [X | lcp(XS, YS)];
lcp(_, _) ->
  [].

Then using lists:foldl to apply it to a list of lists:

lcp([X | XS]) ->
  lists:foldl(fun lcp/2, X, XS).
1> a:lcp(["thisis_a_string123", "thisis_a_nother_string123", "thisis_not_a_string123"]).
"thisis_"
2> a:lcp(["thisis_a_string123", "thisis_a_nother_string123", "thisis_not_a_string123", "xyz"]).
[]
Dogbert
  • 212,659
  • 41
  • 396
  • 397
0

For any number of strings:

lcp([]) -> [];
lcp([S]) -> S;
lcp(L) -> lcp_(L).

lcp_([[H|T]|R]) ->
  case strip(H, R, []) of
    false -> [];
    Ts -> [H|lcp_([T|Ts])]
  end.

strip(_, [], Ts) -> Ts;
strip(H, [[H|T]|R], Ts) -> strip(H, R, [T|Ts]);
strip(_, _, _) -> false.
Hynek -Pichi- Vychodil
  • 26,174
  • 5
  • 52
  • 73