算法思想:整体字符串通过循环判断分别对比指定前后相对位置的字符是否一致,来判断字符串是否为回文。
#include <iostream>
#include <string>
using namespace std;
bool solve(string str) //判断字符串 str 是否为回文
{ int i=0,j=str.length()-1;
while (i<j)
{ if (str[i]!=str[j])
return false;
i++; j--;
}
return true;
}
int main()
{ cout << "求解结果" << endl;
string str="agdhvcdb";
cout << " " << str << (solve(str)?"是回文":"不是回文") << endl;
string str1="abcddcba";
cout << " " << str1 << (solve(str1)?"是回文":"不是回文") << endl;
}
运行测试结果,以字符串agdhvcdb和字符串abcddcba为例:
算法思想:整体数据进行递增排序,求相邻元素之间的差,比较差值,并记录最小元素差,累计最小元素差的个数。
#include <vector>
using namespace std;
int solve(vector<int> &myv) //求 myv相差最小的元素对的个数
{ sort(myv.begin(),myv.end()); //递增排序
int ans=1;
int mindif=myv[1]-myv[0];
for (int i=2;i<myv.size();i++)
{ if (myv[i]-myv[i-1]<mindif)
{ ans=1;
mindif=myv[i]-myv[i-1];
}
else if (myv[i]-myv[i-1]==mindif)
ans++;
}
return ans;
}
int main()
{ int a[]={4,1,2,3};
int n=sizeof(a)/sizeof(a[0]);
vector<int> myv(a,a+n);
cout << "相差最小的元素对的个数: " << solve(myv) << endl;
}
运行测试结果,以题干示例为例: