Skip to content

Instantly share code, notes, and snippets.

@dgodfrey206
Created November 29, 2019 19:51
Show Gist options
  • Save dgodfrey206/7ca1c4ff1e223d0b344acae576bd7736 to your computer and use it in GitHub Desktop.
Save dgodfrey206/7ca1c4ff1e223d0b344acae576bd7736 to your computer and use it in GitHub Desktop.
myString
public class MyString {
private char[] buffer;
private MyString next = null;
private int len = 0;
public MyString(char[] data) {
buffer = data.clone();
len += data.length;
}
public int length() {
return len;
}
private int bufferLen() {
return buffer.length;
}
public void concat(char[] data) {
if (next == null) {
next = new MyString(data);
}
else {
MyString cur = next;
while (cur.next != null) {
cur = cur.next;
}
cur.next = new MyString(data);
}
len += data.length;
}
public String toString() {
if (next != null) {
return new String(buffer) + next.toString();
}
return new String(buffer);
}
public int indexOf(char c) {
int idx = 0;
MyString cur = this;
while (cur != null) {
for (int i=0; i<cur.bufferLen(); i++, idx++) {
if (cur.buffer[i] == c) {
return idx;
}
}
cur = cur.next;
}
return -1;
}
public int lastIndexOf(char c) {
int idx = 0;
int lastIdx = -1;
MyString cur = this;
while (cur != null) {
for (int i=0; i<cur.bufferLen(); i++, idx++) {
if (cur.buffer[i] == c) {
lastIdx = idx;
}
}
cur = cur.next;
}
return lastIdx;
}
private int[] equalUpTo(char[] a, char[] b, int i, int j) {
while (i < a.length && j < b.length) {
if (a[i] != b[j]) {
return null;
}
i++;
j++;
}
return new int[]{i, j};
}
public boolean equals(MyString other) {
if (length() != other.length()) {
return false;
}
if (length() == 0) {
return true;
}
MyString cur1 = this;
MyString cur2 = other;
int i = 0, j = 0;
while (cur1 != null && cur2 != null) {
int[] ret = equalUpTo(cur1.buffer, cur2.buffer, i, j);
if (ret != null) {
if (ret[0] >= cur1.bufferLen() && ret[1] >= cur2.bufferLen()) {
cur1 = cur1.next;
cur2 = cur2.next;
i = j = 0;
} else if (ret[0] >= cur1.bufferLen()) {
cur1 = cur1.next;
i = 0;
j = ret[1];
} else if (ret[1] >= cur2.bufferLen()) {
cur2 = cur2.next;
i = ret[0];
j = 0;
}
} else {
return false;
}
}
return cur1 == null && cur2 == null;
}
public static void main(String[] args) {
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment