题目1 : Longest Subsequence
时间限制:10000ms
单点时限:1000ms
内存限制:256MB
描述
You are given a set of N words W1, W2, ... WN and a target string S. Find the longest word which is also a subsequence of S.
输入
The first line contains an integer N. (1 <= N <= 10000)
The following N lines each contain a word Wi. (1 <= Σ|Wi| <= 100000)
The last line contains the string S. (1 <= |S| <= 100000)
输出
The length of the longest word which is also a subsequence of S.
样例输入
3
a
ac
abc
acbc
样例输出
3
扫描二维码关注公众号,回复:
4722347 查看本文章
#include<string>
using namespace std;
int main()
{
int n;
cin >> n;
string w[10000],s;
for (int i = 0; i < n; i++)
cin >> w[i];
cin >> s;
int Max = 0;
for (int j = 0; j < n; j++)
{
int sum = 0;
for (int k = 0; k < s.length(); k++)
{
if (w[j][sum] == s[k])
sum++;
if (sum == w[j].length())
break;
}
if (sum == w[j].length())
Max = Max > sum ? Max : sum;
}
cout << Max << endl;
return 0;
}
package Daily;
import java.util.Scanner;
import java.util.TreeMap;
import java.util.*;
public class Main_227 {
static class CharPos implements Comparable<CharPos> {
char c;
int pos;
CharPos(char c, int pos) {
this.c = c;
this.pos = pos;
}
char getChar() {
return c;
}
int getPos() {
return pos;
}
public int compareTo(CharPos o) {
if (c == o.c) {
return pos - o.pos;
} else if (c < o.c) {
return -1;
} else {
return 1;
}
}
}
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
String a[] = new String[n];
for (int i = 0; i < n; i++)
{
a[i] = sc.next();
}
String s = sc.next();
TreeMap<CharPos, Integer> m = new TreeMap<>();
for(int i = 0; i < s.length(); i++)
{
m.put(new CharPos(s.charAt(i), i), i);
}
int ans = 0;
for (int i = 0; i < n; i++)
{
int j;
int pos = -1;
for (j = 0; j < a[i].length(); j++)
{
CharPos entry = m.higherKey(new CharPos(a[i].charAt(j), pos));
if (entry == null || entry.getChar() != a[i].charAt(j))
{
pos = -1;
break;
}
else
{
pos = entry.getPos();
}
}
if (pos != -1)
{
ans = Math.max(ans, a[i].length());
}
}
System.out.println(ans);
}
}