通用辅助函数

  • 检查参数
public void checkArguments(String string) {
    if (string == null) {
        throw new RuntimeException("Null string");
    }
}

public void checkArguments(int n) {
    if (n <= 0) {
        throw new RuntimeException("N is less than or equal to zero");
    }
}

public void checkArguments(ListNode head) {
    if (head == null) {
        throw new RuntimeException("Null ListNode");
    }
}

public void checkArguments(int[] array) {
    if (array == null) {
        throw new RuntimeException("Null array");
    }
    if (array.length == 0) {
        throw new RuntimeException("Empty array");
    }

}

public void checkArguments(int[][] matrix) {
    if (matrix == null) {
        throw new RuntimeException("Null matrix");
    }
    if (matrix.lenth == 0) {
        throw new RuntimeException("Empty matrix");
    }

    int col = matrix[0][0].length;
    for (int[] array : matrix) {
        if (array == null) {
            throw new RuntimeException("Null array in matrix");
        }
        if (array.length == 0) {
            throw new RuntimeException("Empty array in matrix");
        }
        if (array.length != col) {
            throw new RuntimeException("Unequal length of array in matrix");
        }
    }
}
  • 工具函数
public void swap(int[] array, int x, int y) {
    int temp = array[x];
    array[x] = array[y];
    array[y] = temp;
}

public void swap(char[] array, int x, int y) {
    char temp = array[x];
    array[x] = array[y];
    array[y] = temp;
}

public void reverse(char[] a, int i, int j) {
    while (i < j) {
        char t = a[i];
        a[i++] = a[j];
        a[j--] = t;
    }
}

public void reverse(StringBuilder sb, int begin, int end) {
    while (begin < end) {
        char temp = sb.charAt(begin);
        sb.setCharAt(begin++, sb.charAt(end));
        sb.setCharAt(end--, temp);
    }
}