2014-01-13 5 views
1
#include <iostream> 

using namespace std; 

int main() 
{ 
    string str = "cab"; 
    string d = ""; 
    char s[] = {'a', 'b', 'c', 'd', 'e'}; 
    for(int i = 0; i < sizeof(s)/sizeof(s[0]); i++){ 
     for(int j = 0; j < str.length(); j++){ 
      if(str[j] == s[i]){ 
       d += s[i]; 
      } 
     } 
    } 
    cout << d << endl; 
    return 0; 
} 

예를 들어 "cab"라는 문자열이 제 경우와 같은 문자 배열에 있는지 확인하고 싶습니다. 문자 배열의 요소 위치에 상관없이 존재해야합니다.문자열 값이 문자 배열에 존재하는지 어떻게 확인할 수 있습니까?

+0

하거나'find'? 정확히이 일을 수행합니다 – user3125280

+0

[std :: includes'] (http://en.cppreference.com/w/cpp/algorithm/includes)를 찾고있는 것 같습니다. –

+0

@JoachimPileborg 틀림없이 find 메소드는 문자열 클래스의 일부이므로 더 빠를 수 있으며 기본적으로 null을 무시합니다. – user3125280

답변

1

하위 문자열에 중복이 없다고 가정하면 unordered_set을 사용할 수 있습니다. 따라서 본질적으로 귀하의 s[]을 반복하고 각 문자에 대해 해당 세트에 해당 문자가 포함되어 있는지 확인하게됩니다.

unordered_set은 O (1) 검색을 허용하므로 알고리즘은 O (n) (n = 크기는 s)에서 실행되어야합니다.

배열 내에있는 문자를 배열에서 찾으면 문자를 제거하고 계속해서 배열을 탐색합니다. 배열을 순회 할 때까지 집합이 비어 있으면 배열에 해당 하위 문자열이 들어 있다는 것을 알게됩니다. 문자를 제거 할 때마다 세트가 비어 있지 않음을 확인할 수도 있습니다. 이렇게하면 실행 시간이 단축됩니다.

1

하지 내 코드 :

#include <string> 
#include <iostream> 
#include <algorithm> 

void print(std::string::size_type n, std::string const &s) 
{ 
    if (n == std::string::npos) { 
     std::cout << "not found\n"; 
    } else { 
     std::cout << "found: " << s.substr(n) << '\n'; 
    } 
} 

int main() 
{ 
    std::string str = "cab"; 
    std::string::size_type n; 
    std::string const s = "This is a string"; 

    // search from beginning of string 
    n = s.find("is"); 
    print(n, s); 

    // search from position 5 
    n = s.find("is", 5); 
    print(n, s); 

    // find a single character 
    n = s.find('a'); 
    print(n, s); 

    // find a single character 
    n = s.find('q'); 
    print(n, s); 

    //not the best way 
    for(char c : s) 
    s.find(c); //will be npos if it doesn't exist 

    //better 
    std::includes(s.begin(), s.end(), 
      str.begin(), str.end()); 
} 
관련 문제