用于计算均匀子串权重的代码

时间:2019-06-15 11:42:02

标签: c++ arrays string c++14

在下面的代码中,我们必须首先计算字符串中存在的统一子字符串的权重。统一子字符串是仅包含一个字符(如“ a”或“ aaa”)的子字符串。 字符的重量定义为 1一 b-2 ...... z-26。

在计算了所有有效的统一子字符串的权重之后,我们将得到各种查询,并且我们必须检查给定的否。是不是数组。

#include<bits/stdc++.h>
using namespace std;

int main()
{
  string s;
  cin>>s;
  int i=0,j=0,k=0;
  int arr[10000];
  int c=0;  
  while(s[i]!='\0')
  {
    int x=(int)s[i];
    x=x-96;
    arr[c++]=x;
    j=i+1;
    int sum=x;
    while(s[j]==s[i])
    {
      sum+=x;
      arr[c++]=sum;
      j++;
    }
    i=j;
  }
  int q;
  cin>>q;
  for(i=0;i<q;i++)
  {
    int val;
    cin>>val;
    bool exists=find(begin(arr),end(arr),val)!=end(arr);
    if(exists==true)
      cout<<"Yes"<<endl;
    else
      cout<<"No"<<endl;
  }
  return 0;
}

输入:

abccddde
6
1
3
12
5
9
10

预期输出:

YES
YES
YES
YES
NO
NO

实际结果:

YES
YES
YES
YES
NO
YES

1 个答案:

答案 0 :(得分:0)

我以一种更简单易懂的方式做到了。我使用std::set存储唯一的可能值,然后使用其find()方法检查查询值是否在集合中。

#include <bits/stdc++.h>
using namespace std;

int main()
{
    string s;
    cin >> s;

    set<int> possible_val;

    int c = 1;
    for (size_t i = 1; i < s.length(); i++) {
        if (s[i] == s[i - 1]) {
            c++;
        }
        else {          // If current char different from previous char
            // If substring is ccc, then put 3, 6 and 9 in the set
            for (int j = 1; j <= c; j++)
                possible_val.insert(j * (s[i - 1] - 'a' + 1));
            // Reset counter to 1
            c = 1;
        }
    }
    for (int j = 1; j <= c; j++)
        possible_val.insert(j * (s[s.length() - 1] - 'a' + 1));

    int q, x;
    cin >> q;
    while (q-- > 0) {
        cin >> x;
        if (possible_val.find(x) != possible_val.end()) cout << "YES\n";
        else cout << "NO\n";
    }
    return 0;
}

我测试问题的链接(通过给定的输入):https://ideone.com/OHfxCq