在字符串数组中查找字符组合

时间:2018-10-06 18:08:44

标签: javascript

我想知道str x的任何组合是否在数组中。一击就已经可以了。

var x = 'ACBC';
var arr = ['X','AB'];
var arr2 = ['X','234','C'];
var arr3 = ['X','CC'];
var arr4 = ['X','BB'];

console.log(containsString(arr,x)) // true
console.log(containsString(arr2,x)) // true
console.log(containsString(arr3,x)) // true
console.log(containsString(arr4,x)) // false

2 个答案:

答案 0 :(得分:2)

您可以对数组进行短路迭代并展开字符串并检查所需字符的位置。

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

int main(int argc, char *argv[])
{
    int *pAge, nBigger, nMale;
    char *pGender;
    int i;

    pAge = (int*)calloc(10, sizeof(int));
    pGender = (char*)calloc(10, sizeof(char));

    if (pAge != NULL && pGender != NULL) {

        for (i = 0; i < 10; i++)
        {
            printf("\n%d. Type your age: ", i + 1);
            scanf("%d", &pAge[i]);

            if (pAge[i] > 40)
            {
                nBigger++;
            }

            printf("\n%d. Type your gender (M / F): ", i + 1);
            scanf("%c", &pGender[i]);

            if (toupper(pGender[i]) == 'M')
            {
                nMale++;
            }
        }

    }
    else {
        printf("Out of memory");
        exit(1);

    }

    printf("\nBigger than 40 y/o: %d", nBigger);
    printf("Male gender: %d", nMale);

    free(pAge);
    free(pGender);

    return 0;
}

虽然以上内容仅适用于排序后的字符串,但您需要预先排序才能与function containsString(array, string) { return array.some(s => [...s].every( (i => c => i = string.indexOf(c, i) + 1)(0) )); } var x = 'ACBC', arr = ['X', 'AB'], arr2 = ['X', '234', 'C'], arr3 = ['X', 'CC'], arr4 = ['X', 'BB']; console.log(containsString(['X', 'AB'], 'ACBC')); // true console.log(containsString(['X', 'BA'], 'ACBC')); // false, see below console.log(containsString(['X', '234', 'C'], 'ACBC')); // true console.log(containsString(['X', 'CC'], 'ACBC')); // true console.log(containsString(['X', 'BB'], 'ACBC')); // false和起始位置更改一起使用。

indexOf

答案 1 :(得分:0)

您可以将x中的char频率与候选字符串的频率进行比较。这是一个解决方案:

var x = 'ACBC';
var arr = ['X', 'AB'];
var arr2 = ['X', '234', 'C'];
var arr3 = ['X', 'CC'];
var arr4 = ['X', 'BB'];

function containsString(list, x) {
  let xFrequencies = frequencies(x);
  return list.some(str => {
    let strFrequencies = frequencies(str);
    return Object.keys(strFrequencies)
      .every(c => c in xFrequencies && strFrequencies[c] <= xFrequencies[c])
  });
}

function frequencies(str) {
  return str.split('').reduce((acc, c) => {
    if (c in acc) acc[c] += 1;
    else acc[c] = 1;
    return acc;
  }, {});
}

console.log(containsString(arr, x)) // true
console.log(containsString(arr2, x)) // true
console.log(containsString(arr3, x)) // true
console.log(containsString(arr4, x)) // false

(感谢Nina Scholz,我了解了someevery:D)