【发布时间】:2017-12-19 17:20:54
【问题描述】:
我试图找出匹配字符串的最佳方法(称为 userInput),其中字符串是来自其他几个字符串(数组列表或数组,在示例中我称为批准)
ArrayList<String> approved = new ArrayList<>();
approved.add("abc");
approved.add("def");
approved.add("ghi");
approved.add("def jkl ggwp my life"); //repeated elements (abc,jkl)
approved.add("jkl");
approved.add("mno");
approved.add("pqr");
approved.add("stu vwx");
approved.add("yz");
为了解释我的困难,我将使用这个数组列表(上图)。但是,在现实世界中,我有一个
-fixed arraylist which wont have dynamic elements (the elements in the arraylist wont change)
-arraylist with more than 6000 elements
-elements in the arraylist contains multiple word e.g ("stu vwx")
-repeated elements but concatenated with another string in the arraylist
如果以下是 userInput
,则程序应返回 trueuserInput = "abc def";
userInput = "stu vwx yz"; //they can combine with another element as a whole
userInput = "ghi"; //it doesnt have to combine with another element
userInput = "vwx yz"; //they can split the arraylist elements with whitespace only and concatenate it with another element
但是,如果以下是 userInput
,程序将 返回 falseuserInput = "yza"; //obviously it doesnt match anything
userInput = "ghi jk"; //doesnt match the concatenated string (ghi and jkl)
userInput = "pqr stu v"; //it can split the element with whitespace,but it has to take the whole word
userInput = "def abc"; //the order are important
我正在考虑拆分 userInput 以获得 firstWord 和 lastWord 因为顺序很重要。然后,使用 contains 在数组列表中查找它们的索引。
我们说
String userInput = "def ghi jkl mno";
//so,the firstWord and lastWord will be
firstWord = "def";
lastWord = "mno";
从这里开始,.contains() 将完成其工作并返回具有字符串 firstWord 和 lastWord 的元素的多个索引(由于firstWord在arraylist中出现了多次),它将被配置为返回另一个数组中可能的匹配项。
firstWordPossibleIndex[] = {1,4};
lastWordPossibleIndex[] = {6};
由于顺序很重要,这里的逻辑是 firstWordPossibleIndex 应该包含比 lastWordPossibleIndex 小的值,所以如果有更大的值,可以将其删除因为提供的字符串是无效的。
在实现该逻辑之后,它应该开始匹配从 firstWordPossibleIndex 到 lastWordPossibleIndex
的下一个索引在这种情况下,它会检查 userInput 中的第二个单词并尝试匹配索引为 2 和 5 的元素(因为 firstWordPossibleIndex 是 1 和4)
它会检查直到lastwordPossibleIndex,如果所有的单词都按照arraylist的顺序,它会返回true。
有了这个,我仍然无法将它连接的字符串与另一个字符串的一部分进行匹配。你有什么办法解决这个问题吗?
有没有图书馆可以解决这个问题?
【问题讨论】:
标签: java android json string-matching