leetcode 187"/>
leetcode 187
leetcode 187
哈希解法
class Solution {const int L = 10;
public:vector<string> findRepeatedDnaSequences(string s) {vector<string> ans;unordered_map<string, int> cnt;int n = s.length();for(int i=0; i<= n-L; ++i){string sub = s.substr(i, L);if(++cnt[sub] == 2){ans.push_back(sub);}}return ans;}
};
哈希+位运算+滑动窗口
A 使用 "00"表示,C使用"01"表示,G使用"10"表示,T使用"11"表示,
根据题目可以知道字符长度为10,所以需要20个0或1组成,
int 是32bit, 字符串是20bit所以可以用int表示字符串的序列,
例如:
00000000000001101111 对应的 int是 431
AAAAAACGTT
string 函数
在 C++ 标准库中,std::string
类型提供了 length()
成员函数来获取字符串的长度。length()
函数返回一个 size_t
类型的值,表示字符串中字符的数量。
以下是使用 length()
函数获取字符串长度的示例:
#include <iostream>
#include <string>int main() {std::string str = "Hello";std::cout << "Length of the string: " << str.length() << std::endl; // 输出 5return 0;
}
在上述示例中,我们创建了一个 std::string
类型的字符串 str
,并使用 length()
函数获取其长度。然后,使用 std::cout
输出字符串的长度。
注意,length()
函数返回的是字符串中字符的数量,而不是字符串占用的字节数。在 C++ 中,std::string
类型使用 UTF-8 编码存储字符串,每个字符可能占用不同数量的字节。
此外,std::string
类型还提供了其他用于获取字符串信息的成员函数,如 size()
、empty()
等。这些函数可以根据具体的需求来使用。
只有0和1的字符串组成int类型
将二进制字符串 “00000000000001101111” 转换为 int
类型的值,可以使用 std::stoi()
函数。以下是示例代码:
#include <iostream>
#include <string>int main() {std::string binaryString = "00000000000001101111"; // 二进制字符串int decimalValue = std::stoi(binaryString, nullptr, 2); // 将二进制字符串转换为 int 类型的值std::cout << "The decimal value is: " << decimalValue << std::endl;return 0;
}
在上述示例中,我们定义了一个名为 binaryString
的字符串变量,并将其初始化为二进制字符串 “00000000000001101111”。然后,我们使用 std::stoi()
函数将二进制字符串转换为 int
类型的值,并将结果存储在 decimalValue
变量中。最后,我们使用 std::cout
和 <<
运算符将 decimalValue
的值打印到控制台。
运行上述代码,输出将是:
The decimal value is: 431
因此,二进制字符串 “00000000000001101111” 转换为 int
类型的值为 431。
更多推荐
leetcode 187
发布评论