題目連結
題意:
每組測資會先告知有若干組替換詞
每兩行分別代表 替換前 與 替換後 ,為一組替換詞
最後是一行原始字串
看似很像word等文書編輯軟體會有的取代功能,但詳讀文章後,會發現有順序性
做法是從第一組替換詞開始搜尋,若有目標(替換前)存在,每次取代 一次
意思是要一步一步來,而不是一次全部換
例如有一組替換詞, AB 換 BA
原本長這樣:ABABAB
一次一次取代:
ABABAB -> BAABAB -> BABAAB -> BBAAAB -> BBAABA
一次全部取代:
ABABAB -> BABABA -> BBABAA -> BBBAAA
(紅色表示當下要被替換的目標)
所以要用String類別的 replaceFirst 方法,而不能用到 replaceAll 方法
最後結果可能有所不同
解法:
程式(Java):
題意:
每組測資會先告知有若干組替換詞
每兩行分別代表 替換前 與 替換後 ,為一組替換詞
最後是一行原始字串
看似很像word等文書編輯軟體會有的取代功能,但詳讀文章後,會發現有順序性
做法是從第一組替換詞開始搜尋,若有目標(替換前)存在,每次取代 一次
意思是要一步一步來,而不是一次全部換
例如有一組替換詞, AB 換 BA
原本長這樣:ABABAB
一次一次取代:
ABABAB -> BAABAB -> BABAAB -> BBAAAB -> BBAABA
一次全部取代:
ABABAB -> BABABA -> BBABAA -> BBBAAA
(紅色表示當下要被替換的目標)
所以要用String類別的 replaceFirst 方法,而不能用到 replaceAll 方法
最後結果可能有所不同
解法:
程式(Java):
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.*; | |
public class Main { | |
public static void main(String args[]){ | |
Scanner sc = new Scanner(System.in); | |
while (sc.hasNext()) { | |
int C = Integer.valueOf(sc.nextLine()); | |
if (C == 0) | |
break; | |
String re[][] = new String[C][2]; | |
for(int i = 0; i < C; i++) { | |
re[i][0] = sc.nextLine(); | |
re[i][1] = sc.nextLine(); | |
} | |
String ori = sc.nextLine(); | |
for(int i = 0; i < C; i++) { | |
while (ori.contains(re[i][0])) { | |
ori = ori.replaceFirst(re[i][0], re[i][1]); | |
} | |
} | |
System.out.println(ori); | |
} | |
} | |
} |
留言
張貼留言