Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create longestpreffix.java #9

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 59 additions & 0 deletions longestpreffix.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
package string;

public class longestpreffix {
static int longestPrefixSuffix(String s) {
int n = s.length();

int lps[] = new int[n];

// lps[0] is always 0
lps[0] = 0;

// length of the previous
// longest prefix suffix
int len = 0;

// the loop calculates lps[i]
// for i = 1 to n-1
int i = 1;
while (i < n) {
if (s.charAt(i) == s.charAt(len)) {
len++;
lps[i] = len;
i++;
}

// (pat[i] != pat[len])
else {
// This is tricky. Consider
// the example. AAACAAAA
// and i = 7. The idea is
// similar to search step.
if (len != 0) {
len = lps[len - 1];

// Also, note that we do
// not increment i here
}

// if (len == 0)
else {
lps[i] = 0;
i++;
}
}
}

int res = lps[n - 1];

// Since we are looking for
// non overlapping parts.
return (res > n / 2) ? n / 2 : res;
}

// Driver program
public static void main(String[] args) {
String s = "abcab";
System.out.println(longestPrefixSuffix(s));
}
}