# Interview Questions – Java: the longest common substequence solution

I saw him today during an interview simulation and I wanted to try it out. I would like to hear your comments. This is the second time I try to solve the problem. Initially, I had a jumble of if / else tricks and nested loops.

``````/ *
* Write a function that takes two strings s1 and s2 and returns the
* The longest common subsequences of s1 and s2.
*
* Examples:
* s1: AGGTAB s2: result of GXTXAYB: GTAB
* s1: yyyy s2: aa result: yy
* s1: yyyy s2: & # 39; result: & # 39; & # 39;
* /
Public class LongestSubsequence {

public static void main (String[] args) {
LongestSubsequence ls = new LongestSubsequence ();

assertEquals ("GTAB", ls.solve ("AGGTAB", "GXTXAYB"));
assertEquals ("aa", ls.solve ("aaaa", "aa"));
assertEquals ("", ls.solve ("aaaa", ""));
}

private String solve (String s1, String s2) {
if (s1.length () == 0 || s2.length () == 0) {
return "";
}

Longest string = (s1.length ()> = s2.length ()? S1: s2);
Shortest string = (s1.length () <s2.length ()? S1: s2);

StringBuilder longestSubsequence = new StringBuilder ();
for (int i = 0; i <longest.length (); i ++) {
char ch = longest.charAt (i);
int firstIndex = shortest.indexOf (ch);
if (firstIndex! = -1) {
longestSubsequence.append (ch);
shortest = shortest.substring (firstIndex + 1);
if (shortest.length () == 0) {
Pause;
}
}
}

returns longestSoussequence.toString ();
}
}
``````