Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/algorithm/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Algorithm 检查输入字符串是否存在于自定义字符串表中_Algorithm_Data Structures - Fatal编程技术网

Algorithm 检查输入字符串是否存在于自定义字符串表中

Algorithm 检查输入字符串是否存在于自定义字符串表中,algorithm,data-structures,Algorithm,Data Structures,假设表中元素的长度为1或2。 表:{h,fe,na,o} 输入字符串:nafeo 输出:真 表:{ab,bc} 输入字符串:abc 输出:false 请告知我下面的代码将涵盖所有情况,这是最好的解决方案吗?或者我遗漏了什么,有没有其他的解决方案 import java.util.*; public class CustomTable { Set<String> table = new HashSet<String>(); public CustomTable(){

假设表中元素的长度为1或2。 表:{h,fe,na,o} 输入字符串:nafeo 输出:真

表:{ab,bc} 输入字符串:abc 输出:false

请告知我下面的代码将涵盖所有情况,这是最好的解决方案吗?或者我遗漏了什么,有没有其他的解决方案

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");

}

}

我认为这个问题与众所周知的问题有相似之处,您可以通过一些定制来使用它的解决方案。

下面的代码是什么?是否要我们编写代码?无法粘贴代码,超出了大小。不确定,这是连续的,自定义表中元素的长度为一或两个。