pat1050

来源:互联网 发布:mac有必要安装office 编辑:程序博客网 时间:2024/06/07 10:25

1050. String Subtraction (20)

时间限制  10 ms  内存限制  32000 kB  代码长度限制  16000 B   判题程序   Standard  作者  CHEN, Yue

Given two strings S1 and S2, S = S1 - S2 is defined to be the remaining string after taking all the characters in S2 from S1.

 Your task is simply to calculate S1 - S2 for any given strings. However, it might not be that simple to do itfast.


Input Specification:

Each input file contains one test case. Each case consists of two lines which gives S1 and S2, respectively.

 The string lengths of both strings are no more than 104. It is guaranteed that all the characters are visible ASCII codes and white space, 

and a new line character signals the end of a string.


Output Specification:

For each test case, print S1 - S2 in one line.


Sample Input:
They are students.aeiou

Sample Output:
Thy r stdnts.
解题思路:
用的是新学到的方法,将出现在S2 中的字符,用一个标定数组对其进行标定,然后在输出S1字符串的时候,
如果S1 中的字符串同样出现在S2中那么必定在 标定数组中有所标示,则不对这个字符进行输出,
如果S1中的字符在S2中没有出现的话, 那么在标定数组中没有标志,所以可以正常输出。
其中标定数组的下标(位序)的取值范围应该合乎于在S1 S2 字符串中出现的字符所对应的Ascii 码的取值范围。
通过出现的 S1或是S2中的字符串  x (x <-{S2[0] ...S2[strlen(S2)-1]}),对应的Ascii 码来表示标志数组mark 的下标;
如果 x 出现在 S2中 :  mark[x] <- true , 否则 : mark[x] <- false ;
然后对 S1 进行扫描, y (y <- {S1[0] ... S1[strlen (S1) -1]}) 
如果, mark[y] == true : 则有结论: y 同时出现在 S1 和S2中, 不能输出 y。
如果, mark[y] == false ; 则有结论: y 出现在 S1 中,但是并不存在于 S2 中, 所以将 y 值进行输出。 
但是必须注意的是,必须对数组 mark 进行初始化, 对其中的所有数组元素的值,均置为 false 才能够保证算法的正常运行。
这种思想,是典型的空间换取时间的算法。
时间复杂度分析:
再读题之后,首先想到的是双重循环双重扫描的方法,不过这个时候看到了时间限制大概只有 10ms,
所以对于长度为不大于  104 的两个字符串的话,O(N^2) 的时间复杂度必定会超时。
所以采用这张方法,将会将时间复杂度减少到 max(O (S1.length ), O(S2.length ))
因为首先对S1 , S2 两个字符串都会进行一个全扫描,并且这两个扫描是并列的,所以时间复杂度为
扫描二者所花费时间最多的那个字符串所花费时间。
代码如下:
#include <cstdio>#include <cstdlib>#include <string.h>/**1005*/using namespace std ;bool mark[260] ;void initMark(){memset( mark , false, sizeof ( mark)) ;}int main ( void ){char l1[10001], l2 [10001] ;initMark() ;gets(l1) ;gets(l2) ;int len1 = strlen(l1) ;int len2 = strlen( l2 ) ;for ( int i = 0 ; i < len2 ; i++ ){ mark[l2[i] ]= true ;}for ( int i = 0 ; i < len1 ; i ++ ){if (!mark[l1[i]]){printf("%c", l1[i]) ;}}return 0 ;}//pat 1050


0 0
原创粉丝点击