最长最短单词
#include <bits/stdc++.h>
using namespace std;
string s, maxv, minv;
int main () {
cin >> s;
s += ' ';
int cont1 = 0, cont2 = 0, maxvv = -1, minvv = 1000;
for (int i = 0; i < s.size (); i++) {
if ((s[i] >= 97 && s[i] <= 122) || (s[i] >= 65 && s[i] <= 90)) {
cont1++;
cont2++;
}
else {
if (cont1 > maxvv) {
maxvv = cont1;
maxv = s.substr (i - maxvv, maxvv);
}
cont1 = 0;
if (cont2 < minvv) {
minvv = cont2;
minv = s.substr (i - minvv, minvv);
}
cont2 = 0;
}
}
cout << maxv << endl << minv;
}
上面是我写的,运行不对,有没有好心人帮我康康
#include <iostream>
#include <string>
using namespace std;
int main() {
string s, maxv, minv;
getline(cin, s);
s += ' ';
int cont1 = 0, cont2 = 0, maxvv = -1, minvv = 1000;
for (int i = 0; i < s.size(); i++) {
if ((s[i] >= 97 && s[i] <= 122) || (s[i] >= 65 && s[i] <= 90)) {
cont1++;
cont2++;
} else {
if (cont1 > maxvv) {
maxvv = cont1;
maxv = s.substr(i - cont1, maxvv);
}
cont1 = 0;
if (cont2 < minvv) {
minvv = cont2;
minv = s.substr(i - cont2, minvv);
}
cont2 = 0;
}
}
cout << maxv << endl << minv;
}
不知道你这个问题是否已经解决, 如果还没有解决的话:1. 线段树是一棵二叉树,其节点表示的是一个区间 [ x , y ]
2. 每一个叶子节点表示了一个单位区间,根节点表示的是“整体”的区间。
3. 每个非叶子节点的区间 [ x , y ]
其左儿子节点的区间 [ x , ( x + y ) / 2 ]
其右儿子节点的区间 [ ( x + y ) / 2 +1,y]
针对你的问题,关于找到字符串中最长和最短单词的方法,我可以给出这样一个解决方案:
首先,你可以使用C++的字符串流来将字符串分割为单词。具体步骤如下:
#include <sstream> // 字符串流
#include <vector> // 向量
#include <string> // 字符串
#include <algorithm> // 算法
std::vector<std::string> SplitStringIntoWords(const std::string& str) {
std::istringstream iss(str); // 创建字符串流
std::vector<std::string> words; // 创建存储单词的向量
std::string word;
while (iss >> word) {
words.push_back(word);
}
return words;
}
void FindLongestAndShortestWords(const std::string& str, std::string& longestWord, std::string& shortestWord) {
std::vector<std::string> words = SplitStringIntoWords(str);
// 找到最长和最短单词
longestWord = *std::max_element(words.begin(), words.end(), [](const std::string& a, const std::string& b) {
return a.length() < b.length();
});
shortestWord = *std::min_element(words.begin(), words.end(), [](const std::string& a, const std::string& b) {
return a.length() < b.length();
});
}
通过上述代码,你可以将给定的字符串划分为单词,并找到其中的最长和最短单词。你可以通过以下方式调用这些函数来解决你的问题:
std::string str = "This is a test string";
std::string longestWord, shortestWord;
FindLongestAndShortestWords(str, longestWord, shortestWord);
std::cout << "Longest word: " << longestWord << std::endl;
std::cout << "Shortest word: " << shortestWord << std::endl;
这样,你就可以找到给定字符串中的最长和最短单词了。
希望我的解答能帮到你!如果你还有其他问题,欢迎继续提问。