0
假設在表元素的長度爲1個或2 表:{H,鐵,鈉,鄰} 輸入字符串:nafeo 輸出:真要檢查的輸入串存在於字符串的定製表格
表:{AB,BC} 輸入字符串:ABC 輸出:假
請告知我下面的代碼將覆蓋所有的情況下,這是最好的解決辦法?或者我錯過了任何其他解決方案?
import java.util.*;
public class CustomTable {
Set<String> table = new HashSet<String>();
public CustomTable(){
// add your elements here for more test cases
table.add("oh");
table.add("he");
}
public int checkTable(String prev, String curr, String next) {
System.out.print(prev+":"+curr+":"+next);
System.out.println();
if (prev!=null) if (table.contains(prev)) return -1;
if (table.contains(curr)) return 0;
if (table.contains(next)) return 1;
return 2;
}
// ohhe.
public static void main(String args[]) {
CustomTable obj = new CustomTable();
String inputStr = "ohheo"; //Tested ohe,ohhe,ohohe
int result = 0;
String curr, prev, next;
for (int i = 0; i < inputStr.length(); i++) {
// if prev element is found
if (result==-1){
prev = null;
}
else {
if (i > 0) {
prev = inputStr.substring(i - 1, i + 1);
} else {
prev = inputStr.substring(i, i + 1);
}
}
curr = inputStr.substring(i,i+1);
if (i < inputStr.length()-1) {
next = inputStr.substring(i, i+2);
} else {
next = inputStr.substring(i, i+1);
}
result = obj.checkTable(prev, curr, next);
if (result==2) {
System.out.print("false");
return;
}
}
System.out.print("true");
}
}
下面的代碼?你想讓我們寫代碼嗎? – Haris
無法粘貼代碼,超出尺寸。 – pressf1