class VectorUtil {

	public static SparseVector parseSparse(String str) {
		try {
			if (org.apache.flink.util.StringUtils.isNullOrWhitespaceOnly(str)) {
				return new SparseVector();
			}

			int n = -1;
			int firstDollarPos = str.indexOf(HEADER_DELIMITER);
			int lastDollarPos = -1;
			if (firstDollarPos >= 0) {
				lastDollarPos = StringUtils.lastIndexOf(str, HEADER_DELIMITER);
				String sizeStr = StringUtils.substring(str, firstDollarPos + 1, lastDollarPos);
				n = Integer.valueOf(sizeStr);
				if (lastDollarPos == str.length() - 1) {
					return new SparseVector(n);
				}
			}

			int numValues = StringUtils.countMatches(str, String.valueOf(INDEX_VALUE_DELIMITER));
			double[] data = new double[numValues];
			int[] indices = new int[numValues];
			int startPos = lastDollarPos + 1;
			int endPos;
			for (int i = 0; i < numValues; i++) {
				int colonPos = StringUtils.indexOf(str, INDEX_VALUE_DELIMITER, startPos);
				if (colonPos < 0) {
					throw new IllegalArgumentException("Format error.");
				}
				endPos = StringUtils.indexOf(str, ELEMENT_DELIMITER, colonPos);

				//to be compatible with previous delimiter
				if (endPos == -1) {
					endPos = StringUtils.indexOf(str, ",", colonPos);
				}

				if (endPos == -1) {
					endPos = str.length();
				}
				indices[i] = Integer.valueOf(str.substring(startPos, colonPos).trim());
				data[i] = Double.valueOf(str.substring(colonPos + 1, endPos).trim());
				startPos = endPos + 1;
			}
			return new SparseVector(n, indices, data);
		} catch (Exception e) {
			throw new IllegalArgumentException(
				String.format("Fail to getVector sparse vector from string: \"%s\".", str),
				e);
		}
	}

}