Mike and strings //find()函数的使用

A - Mike and strings
Mike has n strings s1, s2, …, sn each consisting of lowercase English letters. In one move he can choose a string si, erase the first character and append it to the end of the string. For example, if he has the string “coolmike”, in one move he can transform it into the string “oolmikec”.
Now Mike asks himself: what is minimal number of moves that he needs to do in order to make all the strings equal?

**问题分析:**题意是说给定几个字符串然后问最少移动需要几步才能把这几个字符串移为一样的;(移动规则是把首字母移动到尾部)
**解题思路:**首先需要知道#include带的函数 find();

string1.find(string2)

这个函数意思是在string1中查询是否存在string2若存在返回string2在string1中首字符的地址下标 若查询不到则返回 string::npos ;这个npos是一个-1或者很大的数。
其次就是本题一个巧妙之处 把移动的函数复制一遍 作为string1然后在string1中查询string2(模板字符串)
例如:4
xzzwo
zwoxz
zzwox
xzzwo
string1:(xzzwoxzzwo) string2 :zwoxz(模板字符串) 明显看出stringg2出现在 3 则需要移动三步 此为本题主要解题关键
实现代码:

#include<iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include<string>
using namespace std;
 
const int N = 100 + 10;
string a[N];
 
int main()
{
    int n;
    while(scanf("%d",&n) == 1)//若i=1则继续循环否则退出
    {
        for(int i = 0; i < n; i++)
            cin>>a[i];
        int ans = 0x3f3f3f, flag = 0; //ans是一个很大的数
        for(int i = 0; i < n; i++)//以每个字符串目标模板 看需要移动几步最后找出最少步数的模板
        {
            int sum = 0;
            for(int j = 0; j < n; j++)
            {
                string tmp = a[j] + a[j];//将当前找的这个字符串复制两遍在这个复制两遍的字符串里找a[i]出现的位置返回的坐标就是需要移动的步数
                if(tmp.find(a[i]) == string::npos) flag = 1;//string自带的find()string1中查找string2,
                else 
                {
                   sum += tmp.find(a[i]) ;//string1.find(string2)将返回string2第一次在string1中出现的位置
                   
                } ;
            }
         ans = min(ans, sum);
        }
        printf("%d\n", flag ? -1 : ans); //就是if(flag)cout<<-1 else cout<<ans;
    }
}

分享如上,如有问题望读者指出,若有不解可留言作者一定给予解惑。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值