Skip to content

Adding Manacher's algorithm to Java/strings. #2015

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

Closed
wants to merge 19 commits into from
Closed
Changes from 1 commit
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
Prev Previous commit
Next Next commit
Added new Java file LongestSubstringWithoutDuplication.java
  • Loading branch information
AzadN committed Nov 4, 2020
commit e72d622aaf15ae7317e8f6959353aceda4234d4c
28 changes: 28 additions & 0 deletions strings/LongestSubstringWithoutDuplication.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import java.util.*;

public class LongestSubstringWithoutDuplication {

public static void main(String[] args) {
// Testcases
assert longestUniqueSubstring("lmnoppqrrsss").equals("lmnop");
assert longestUniqueSubstring("falafel").equals("lafe");
assert longestUniqueSubstring("krishnamachari").equals("krishnam");
}

// Finds the longest substring of a string having unique characters
public static String longestUniqueSubstring(String str) {
if (str.equals("")) return "";
HashMap<Character, Integer> lastSeenAt = new HashMap<>();
int[] longest = new int[] { 0, 1 };
int start = 0;
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (lastSeenAt.containsKey(c)) start =
Math.max(start, lastSeenAt.get(c) + 1);
if (longest[1] - longest[0] < i + 1 - start) longest =
new int[] { start, i + 1 };
lastSeenAt.put(c, i);
}
return str.substring(longest[0], longest[1]);
}
}