Download String Manipulation and Sorting Algorithms in Java and more Slides Data Representation and Algorithm Design in PDF only on Docsity!
6. Strings
2
Strings
String. Sequence of characters.
Ex. Natural languages, Java programs, genomic sequences, …
The digital information that underlies biochemistry, cell biology, and development can be represented by a simple string of G's, A's, T's and C's. This string is the root data structure of an organism's biology. - M. V. Olson 3
Using Strings in Java
String concatenation. Append one string to end of another string.
Substring. Extract a contiguous list of characters from a string.
String s = "strings"; // s = "strings" char c = s.charAt( 2 ); // c = 'r' String t = s.substring( 2 , 6 ); // t = "ring" String u = s + t; // u = "stringsring" s t r i n g s 0 1 2 3 4 5 6 4
Implementing Strings In Java
Memory. 4 0 + 2N bytes for a virgin string!
public final class String implements Comparable { private char[] value; // characters private int offset; // index of first char into array private int count; // length of string private int hash; // cache of hashCode() private String(int offset, int count, char[] value) { this.offset = offset; this.count = count; this.value = value; } public String substring(int from, int to) { return new String(offset + from, to - from, value); } … } could use byte array instead of String to save space java.lang.String
5
String vs. StringBuilder
String. [immutable] Fast substring, slow concatenation.
StringBuilder. [mutable] Slow substring, fast (amortized) append.
public static String reverse(String s) { String rev = ""; for (int i = s.length() - 1 ; i >= 0 ; i--) rev += s.charAt(i); return rev; } quadratic time public static String reverse(String s) { StringBuilder rev = new StringBuilder(); for (int i = s.length() - 1 ; i >= 0 ; i--) rev.append(s.charAt(i)); return rev.toString(); } linear time 6 public static String lcp(String s, String t) { int n = Math.min(s.length(), t.length()); for (int i = 0 ; i < n; i++) { if (s.charAt(i) != t.charAt(i)) return s.substring( 0 , i); } return s.substring( 0 , n); }
Longest Common Prefix
Longest common prefix. Given two strings, find the common prefix
that is as long as possible.
p r e f i x 0 1 2 3 4 5 6 p r e f e t c 7 h
Radix Sorting
8
Radix Sorting
Radix sorting.
! Specialized sorting solution for strings.
! Same ideas for bits, digits, etc.
Applications.
! Bioinformatics.
! Sorting strings.
! Full text indexing.
! Plagiarism detection.
! Burrows-Wheeler transform. [see data compression]
13
Suffix Sorting: Java Implementation
public class LRS { public static void main(String[] args) { String s = StdIn.readAll(); int N = s.length(); String[] suffixes = new String[N]; for (int i = 0 ; i < N; i++) suffixes[i] = s.substring(i, N); Arrays.sort(suffixes); String lrs = ""; for (int i = 0 ; i < N - 1 ; i++) { String x = lcp(suffixes[i], suffixes[i+ 1 ]); if (x.length() > lrs.length()) lrs = x; } System.out.println(lrs); } } read input create suffixes (linear time) sort suffixes % java LRS < mobydick.txt ,- Such a funny, sporty, gamy, jesty, joky, hoky-poky lad, is the Ocean, oh! Th find longest match 14
String Sorting Performance
Quicksort W N log N †^9. 5 Worst Case Moby Dick Brute W N^2 36 , 000 § String Sort Suffix (sec) W = max length of string N = number of strings
- 2 million for Moby Dick § estimate † probabilistic guarantee
LSD Radix Sort
16
String Sorting Notation
Notation.
! String = sequence of characters.
! W = max # characters per string.
! N = # input strings.
! R = radix.
Java syntax.
! Array of strings: String[] a
! Number of strings: N = a.length
! The ith^ string: a[i]
! The dth^ character of the ith^ string: a[i].charAt(d)
! Strings to be sorted: a[ 0 ], …, a[N- 1 ]
256 for extended ASCII, 65,536 for original Unicode
18
Key Indexed Counting
Key indexed counting.
! Count frequencies of each letter. [ 0 th^ character]
d a b a d d c a b f a d f e e b a d d a d b e e f e d b e d e b b a c e 0 1 2 3 4 5 6 7 8 9 10 11 a 0 b 2 c 3 d 1 e 2 f 1 g 3 int N = a.length; int[] count = new int[ 256 + 1 ]; for (int i = 0 ; i < N; i++) { char c = a[i].charAt(d); count[c+ 1 ]++; } frequencies a count d = 0 19
Key Indexed Counting
Key indexed counting.
! Count frequencies of each letter. [ 0 th^ character]
! Compute cumulative frequencies.
for (int i = 1 ; i < 256 ; i++) count[i] += count[i- 1 ]; cumulative counts a 0 b 2 c 5 d 6 e 8 f 9 g d a b a d d c a b f a d f e e b a d d a d b e e f e d b e d e b b a c e 0 1 2 3 4 5 6 7 8 9 10 11 12 a count a 0 b 2 c 3 d 1 e 2 f 1 g 3 32
Key Indexed Counting
Key indexed counting.
! Count frequencies of each letter. [ 0 th^ character]
! Compute cumulative frequencies.
! Use cumulative frequencies to rearrange strings.
a 1 b 5 c 6 d 8 e 9 f 12 a d d a c e b a d b e e b e d c a b d a b d a d e b b f a d f e e f e d 0 1 2 3 4 5 6 7 8 9 10 11 g 12 d a b a d d c a b f a d f e e b a d d a d b e e f e d b e d e b b a c e 0 1 2 3 4 5 6 7 8 9 10 11 2 a temp rearrange for (int i = 0 ; i < N; i++) { char c = a[i].charAt(d); temp[count[c]++] = a[i]; } count 33
Key Indexed Counting
Key indexed counting.
! Count frequencies of each letter. [ 0 th^ character]
! Compute cumulative frequencies.
! Use cumulative frequencies to rearrange strings.
a 2 b 5 c 6 d 8 e 9 f 12 0 1 2 3 4 5 6 7 8 9 10 11 a d d a c e b a d b e e b e d c a b d a b d a d e b b f a d f e e f e d 0 1 2 3 4 5 6 7 8 9 10 11 g 12 for (int i = 0 ; i < N; i++) a[i] = temp[i]; copy back a count temp a d d a c e b a d b e e b e d c a b d a b d a d e b b f a d f e e f e d
MSD Radix Sort
39
Most significant digit radix sort.
! Partition file into 256 pieces according
to first character.
! Recursively sort all strings that start
with the same character, etc.
Q. How to sort on dth^ character?
A. Key-indexed counting.
MSD Radix Sort
40
MSD Radix Sort Implementation
public static void msd(String[] a) { msd(a, 0 , a.length, 0 ); } private static void msd(String[] a, int l, int r, int d) { if (r <= l + 1 ) return; // key-indexed counting sort on digit d of a[l] to a[r] int[] count = new int[ 256 + 1 ]; ... // recursively sort 255 subfiles – assumes '\ 0 ' terminated for (int i = 0 ; i < 255 ; i++) msd(a, l + count[i], l + count[i+ 1 ], d+ 1 ); } inclusive exclusive 41
String Sorting Performance
Quicksort LSD * MSD W N log N † W(N + R) W(N + R)
- 5
395 Worst Case Moby Dick Brute W N^2 36 , 000 § String Sort Suffix (sec) R = radix W = max length of string N = number of strings
- 2 million for Moby Dick § estimate
- fixed length strings only † probabilistic guarantee
42
MSD Radix Sort: Small Files
Disadvantages.
! Too slow for small files.
- ASCII: 100x slower than insertion sort for N = 2
- Unicode: 30,000x slower for N = 2
! Huge number of recursive calls on small files.
Solution. Cutoff to insertion sort for small N.
Consequence. Competitive with quicksort for string keys.
43
String Sorting Performance
Quicksort LSD * MSD MSD with cutoff W N log N † W(N + R) W(N + R) W(N + R)
- 5
395
- 8 Worst Case Moby Dick Brute W N^2 36 , 000 § String Sort Suffix (sec) R = radix W = max length of string N = number of strings
- 2 million for Moby Dick § estimate
- fixed length strings only † probabilistic guarantee 44
Recursive Structure: MSD
Recursive structure. R-way branching leads to lots of empty calls.
3-Way Radix Quicksort
50
String Sorting Performance
§ estimate
- fixed length strings only † probabilistic guarantee Quicksort LSD * MSD MSD with cutoff W N log N † W(N + R) W(N + R) W(N + R)
- 5
395
- 8 Worst Case Moby Dick Brute W N^2 36 , 000 § 3 - way radix quicksort W N log N †^2. 8 String Sort Suffix (sec) R = radix W = max length of string N = number of strings
- 2 million for Moby Dick 51
Suffix Sorting: Worst Case Input
Input: "abcdeghiabcdefghi" abcdefghi abcdefghiabcdefghi bcdefghi bcdefghiabcdefghi cdefghi cdefghiabcdefgh defghi efghiabcdefghi efghi fghiabcdefghi fghi ghiabcdefghi fhi hiabcdefghi hi iabcdefghi i
Length of longest match small.
! Hard to beat 3-way radix quicksort.
Length of longest match very long.
! 3-way radix quicksort is quadratic.
! Ex: two copies of Moby Dick.
Can we do better? !(N log N)? !(N)?
Observation. Must find longest repeated
substring while suffix sorting to beat N^2.
52
Suffix Sorting in Linearithmic Time: Key Idea
0 babaaaabcbabaaaaa 0 1 abaaaabcbabaaaaa 0 b 2 baaaabcbabaaaaa 0 ba 3 aaaabcbabaaaaa 0 bab 4 aaabcbabaaaaa 0 baba 5 aabcbabaaaaa 0 babaa 6 abcbabaaaaa 0 babaaa 7 bcbabaaaaa 0 babaaaa 8 cbabaaaaa 0 babaaaab 9 babaaaaa 0 babaaaabc 10 abaaaaa 0 babaaaabcb 11 baaaaa 0 babaaaabcba 12 aaaaa 0 babaaaabcbab 13 aaaa 0 babaaaabcbaba 14 aaa 0 babaaaabcbabaa 15 aa 0 babaaaabcbabaaa 16 a 0 babaaaabcbabaaaa 17 0 babaaaabcbabaaaaa 17 0 bab aaaa bcbabaaa aa 16 a 0 ba baaa abcbabaa aa 15 aa 0 b abaa aabcbaba aa 14 aaa 0 baba aaabcbab aa 3 aaaa bcba baaaaa 0 b ab 12 aaaa a 0 ba baaaabcb ab 13 aaaa 0 bab aaaabcba ba 4 aaab cbab aaaaa 0 ba ba 5 aabc baba aaaa 0 bab aa 1 abaa aabc babaaaaa 0 b 10 abaa aaa 0 babaaaab cb 6 abcb abaa aaa 0 baba aa 2 baaa abcb abaaaaa 0 ba 11 baaa aa 0 b abaaaabc ba 0 baba aaab cbabaaaa a 0 9 baba aaaa 0 babaaaa bc 7 bcba baaa aa 0 babaa aa 8 cbab aaaa a 0 babaaa ab text = "babaaaabcbabaaaaa" 0 + 4 = 4 sorted 9 + 4 = 13 53
Suffix Sorting in Sub-Quadratic Time
Manber's MSD algorithm.
! Phase 0: sort on first character using key-indexed sorting.
! Phase i: given list of suffixes sorted on first 2 i-^1 characters,
create list of suffixes sorted on first 2i^ characters
! Finishes after lg N phases.
Manber's LSD algorithm.
! Same idea but go from right to left.
! O(N log N) guaranteed running time.
! O(N) extra space (but need several auxiliary arrays).
Best in theory. O(N) but more complicated to implement.
54
String Sorting Performance
§ estimate
- fixed length strings only † probabilistic guarantee ‡ suffix sorting only Quicksort LSD * MSD MSD with cutoff W N log N † W(N + R) W(N + R) W(N + R)
- 5
395
- 8 Worst Case Moby Dick Brute W N^2 36 , 000 § 3 - way radix quicksort Manber ‡ W N log N † N log N
- 8 17 String Sort Suffix Sort (seconds) 167
memory 162 3 , 990 § 400
- 5 AesopAesop R = radix W = max length of string. N = number of strings
- 921 mtihloliousna fnodr fMoro bAye (^) sDoicpk's Fables