本系列不作为一个全面的语法梳理,只是笔者在写程序时遇到的一些有趣的现象,寻思着以后如果写程序注意这些点,也许可以使得程序速度提升。
考虑这个简单的问题:比较 string word,是否与 string s的第 i到j位的子字符串相等。
自然地,我们可以这样写
bool strEq(string & word, string & s, int i, int j){
if (word.size() == j-i+1)
return word == s.substr(i, j-i+1);
else
return false;
}
这借助了 std里面 string自带的method substr。
然而,今天笔者在写一道数据结构题目时,发现这个方法效率极其低下。
题目链接:https://leetcode-cn.com/problems/re-space-lcci/ [面试题 17.13. 恢复空格]
这个题本身也还算有意思,是一个DP问题,想到代码如下:
class Solution {
public:
int respace(vector<string>& dictionary, string sentence) {
int N = sentence.size();
if (N==0