interviewstreet-string similarity – 類別-string process

來源:互聯網
上載者:User

題目來源:https://www.interviewstreet.com/challenges/dashboard/#problem/4edb8abd7cacd

解題報告:

簡單的字串處理,對S的每個尾碼,計算它與S的相似性,相似性計算是用遞迴做的。

#include <iostream>#include <string.h>using namespace std;int getSim(char* str1, char* str2){    if ( *str1 == '\0' || *str2 == '\0')        return 0;    if (*str1 != *str2)        return 0;    if ( *str1 == *str2)        return 1 + getSim(str1+1, str2+1);}int main(){    char * s = new char[100000];    int N;    cin >> N;    for (int i = 0; i < N; i++)    {        int similarity = 0;        cin >> s;        similarity += strlen(s);        for (int i = 1; i < strlen(s); i++)        {            similarity += getSim(s, s + i);        }        cout << similarity << endl;    }}

附錄:

String Similarity (25 Points)

For two strings A and B, we define the similarity of the strings to be the length of the longest prefix common to both strings. For example, the similarity of strings "abc" and "abd" is 2, while the similarity of strings "aaa" and "aaab" is 3.

Calculate the sum of similarities of a string S with each of it's suffixes.

Input:
The first line contains the number of test cases T. Each of the next T lines contains a string each.

Output:
Output T lines containing the answer for the corresponding test case.

Constraints:
1 <= T <= 10
The length of each string is at most 100000 and contains only lower case characters.

Sample Input:
2
ababaa
aa

Sample Output:
11
3

Explanation:
For the first case, the suffixes of the string are "ababaa", "babaa", "abaa", "baa", "aa" and "a". The similarities of each of these strings with the string "ababaa" are 6,0,3,0,1,1 respectively. Thus the answer is 6 + 0 + 3 + 0 + 1 + 1 = 11.

For the second case, the answer is 2 + 1 = 3.

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.