Partition Labels
A string S of lowercase letters is given. We want to partition this string into as many parts as possible so that each letter appears in at most one part, and return a list of integers representing the size of these parts.
Example 1:
Input: S = “ababcbacadefegdehijhklij”
Output: [9,7,8]
Explanation:
The partition is “ababcbaca”, “defegde”, “hijhklij”.
This is a partition so that each letter appears in at most one part.
A partition like “ababcbacadefegde”, “hijhklij” is incorrect, because it splits S into less parts.
Note:
S will have length in range [1, 500].
S will consist of lowercase letters (‘a’ to ‘z’) only.
Solution:
随机给定一个字符串序列,按规则分段,保证每个字母只出现在其中一个序列中
思路:
- 用map来存储给定字母的最后一个下标
#include <string>
#include <vector>
#include <map>
//#include <tr1/unordered_map>
#include <iostream>
using namespace std;
//using namespace std::tr1;
map<int, string> splitString(string& str)
{
map<char,int> srcmp;
map<int, string> res;
if (str.empty()) return res;
for(int i = 0; i < str.size(); i++) srcmp[str[i]] = i;
for(int j = 0; j < str.size(); j++)
{
int pos = max(j, srcmp[str[j]]);
res.insert(make_pair<int, string>(pos -j + 1, str.substr(j, pos -j + 1)));
while(j != pos) {
j++;
}
}
return res;
}
int main()
{
string str = "abcdaembuijejjdfslfdoefetjljroglwfjfwlfjosiff";
map<int, string> res = splitString(str);
map<int, string>::iterator it = res.begin();
cout << "Original String: " << str << endl;
while(it != res.end())
{
cout << it->first << ": " << it->second << endl;
it++;
}
cout << endl;
return 1;
}
小注:
在C++早期版本标准库里面只有map这个字典,内部实现是采用的红黑树。对于字典这类结构也可以用hash表来实现,也就是C++的标准库应该也要有hash_map这种数据结构。
- 红黑树实现的map占用内存较小,但是查找效率不高,O(logn)的查找效率。
- hash表实现的map占用内存较大,但是查找效率高,往往可以逼近O(1)的惊人查找效率。
在C++中关于map的hash表方法的实现是unordered_map这个数据结构,首次出现应该是在C++98那个年代的tr1这个命名空间里面出现:
#include <tr1/unordered_map>
using std::tr1::unordered_map;
c++0x/c++11标准才把unordered_map纳入std标准, 也就是只有在支持-std=c++0x甚至-std=c++11的编译器里(对于g++来说大概是g++4.4这个版本以上的才开始支持),才可以用如下代码使用unordered_map:
#include <unordered_map>
using std::unordered_map;