leetcode763 划分字母区间 方法2

#include <map>
using namespace std;
class Solution {
public:
	vector<int> partitionLabels(string S) {
		vector<int> ans;
		map<int, int> m;
		for (int i = 0; i < S.size(); i++) {
			m[S[i]] = i;
		}
		/*for (auto item : m) {
			cout << item.first << "---" << item.second << endl;
		}*/
		int start = 0;
		int end = 0;
		for (int i = 0; i < S.size();i++) {
			// 第一次出现任意一个字母的 就把最终的区间给订好了
			end = max(end, m[S[i]]);
			if (end == i) {
				ans.push_back(end - start + 1);
				// update start
				start = end + 1;
			}
			
		}
		return ans;
	}
};

猜你喜欢

转载自blog.csdn.net/weixin_36149892/article/details/80300111