Delete Digits

Description:

Given string A representative a positive integer which has N digits, remove any k digits of the number, the remaining digits are arranged according to the original order to become a new positive integer.

Find the smallest integer after remove k digits.

N <= 240 and k <= N,

Example

Given an integer A = "178542", k = 4

return a string "12"

Solution:

class Solution {
public:
	/**
	 *@param A: A positive integer which has N digits, A is a string.
	 *@param k: Remove k digits.
	 *@return: A string
	 */
	string DeleteDigits(string A, int k) {
		auto sz = (int)A.length();
		if (sz == 0) return "0";
		string rc = "0";
		int cnt = 0;
		for (int i = 0; i < sz; ++i) {
			auto ch = A[i];
			while (cnt < k && ch < rc.back()) {
				++cnt;
				rc.pop_back();
			}
			rc.push_back(ch);
		}
		while (cnt < k) {
			rc.pop_back();
			++cnt;
		}
		int pos = 0;
		while (pos < rc.length() && rc[pos] == '0') ++pos;
		return pos == rc.length() ? "0" : rc.substr(pos);
	}
};
posted @ 2015-09-10 21:59  影湛  阅读(127)  评论(0)    收藏  举报