字符串的空白符包括:空格、制表符 tab、换行符等其他空白符等。
今天看到一个与平时不一样的算法,因此,第一时间想跟大家分享一下。
#define TRIM(s, chars) \
do{ \
string map(0xFF, '\0'); \
for (auto &ch : chars) { \
map[(unsigned char &)ch] = '\1'; \
} \
while( s.size() && map.at((unsigned char &)s.back())) s.pop_back(); \
while( s.size() && map.at((unsigned char &)s.front())) s.erase(0,1); \
}while(0);
//去除前后的空格、回车符、制表符
std::string &trim(std::string &s, const string &chars=" \r\n\t") {
TRIM(s, chars);
return s;
}
std::string trim(std::string &&s, const string &chars=" \r\n\t") {
TRIM(s, chars);
return std::move(s);
}
个人感觉,最核心和最巧妙的地方是,这个算法将“空格、回车、换行、tab”等,存入一个长度为255的string,与空白字符索引相同的值设为1,其他设为0。
然后,遍历源字符串s的尾部和首部字符,如果该字符在map字符串中对应的值为‘\1’,那么,就执行pop操作。
通过这种实现方式,可以做到O(n)的时间复杂度。
如果,每次字符比对,还要遍历一次空白字符集,那么,时间复杂度就是O(n*n)了。