我有一個包含"a"
,"b"
,"ab"
,"ab c"
, "ab cd"
的短語ArrayList。 輸入可能是"ab c"
或"ab c"
。在任何情況下,它都應該與ArrayList中的"ab c"
匹配。我需要一個算法。搜索字符串,不考慮空白
0
A
回答
0
我不知道你使用的是什麼語言,但最簡單的僞代碼:
f(string inString, ArrayList<string> list):
string s = inString.removeAllWhitespace();
foreach (string s2 in list):
string lString = s2.removeAllWhitespace();
if (s.equals(lString))
return true
return false
如果你希望它是更快,嘗試是這樣的:
f(string inString, ArrayList<string> list):
foreach (string s in list):
i1 = 0
i2 = 0
while (i1 < inString.length && i2 < s.length):
if (iswhitespace(inString[i1])):
i1++
else if (iswhitespace(s[i2])):
i2++
else if (inString[i1] == s[i2]):
i1++
i2++
else:
continue foreach
# account for trailing whitespace in both strings
while (i1 < inString.length):
if (!iswhitespace(inString[i1])):
break
i1++
while (i2 < s.length):
if (!iswhitespace(s[i2])):
break
i2++
# strings are equal if we reached the end of both without
# finding different characters (ignoring whitespace)
if (i1 == inString.length && i2 == s2.length):
return true
return false
這將遍歷具有唯一索引的每個字符串,當找到空白或匹配時遞增。如果字符不匹配,則字符串被拒絕,外部循環繼續。
這個僞代碼沒有經過測試,但應該給你一個如何去做的想法。我建議去刪除空白路線。這是更簡單的代碼,不是太慢,給讀者非常明顯的線索,你想要做什麼。
在大多數語言中,字符串是不可變的,所以這種替換不會影響ArrayList中的字符串。
1
你真正要問的是如何用一個空格替換多個空格。這可能是你所需要的:See this question.
0
bool hacked_compare(const string& s, const string& t){
string::const_iterator si = s.begin(), ti = t.begin();
while (si != s.end() && ti != t.end() && (isspace(*si) || isspace(*ti))){
// ignore all spaces leading to next char.
while (si != s.end() && isspace(*si))
si++;
while (ti != t.end() && isspace(*ti))
ti++;
// check for equality of two chars.
if (*si != *ti)
return false;
// keep going through both strings.
si++;
ti++;
}
//if we got this far then the strings were "equivalent" or empty.
return true;
}
+0
做了最小的測試,但這應該做到這一點,你不會需要複製任何字符串,甚至創建本地字符串的臨時副本,它應該是很大的O(n),所以它的性能就如你所能得到的那樣好。 –
相關問題
- 1. 字符串格式不考慮字符串中的空格
- 2. 反序列化字符串考慮空單爲空字符串
- 3. 定期Expression-搜索空白和非空白字符串
- 4. SQL Server WHERE條件不考慮空白
- 5. Serializable類不考慮字符串屬性
- 6. Solr的搜索查詢不考慮特殊字符
- 7. 如何搜索perl中不包含空白的字符串
- 8. Solr子串空白搜索
- 9. jpa標準不考慮空格比較兩個字符串
- 10. 比較目標C中的兩個字符串,不考慮大小寫,標點符號和空白字符
- 11. 考慮在查詢中爲空字符串爲空
- 12. 考慮數字的字符串比較
- 13. 用分隔符連接字符串並考慮到空字符串
- 14. 全文搜索會考慮索引嗎?
- 15. 考慮到在搜索中的特殊字符
- 16. 排序表考慮空白單元格
- 17. Java MYSQL,忽略空白字符串的搜索
- 18. PHP字符串比較考慮在
- 19. 如何創建一個考慮空變量的字符串?
- 20. 空白/空搜索表單字段
- 21. 在PHP搜索字符串,搜索字段包含空格
- 22. Tweepy空白搜索
- 23. 空格分隔MySQL字符串搜索
- 24. Sitecore + Lucene搜索FieldQuery和空字符串
- 25. 搜索字符串
- 26. 字符串搜索
- 27. 搜索字符串
- 28. 搜索字符串
- 29. 搜索字符串
- 30. 搜索字符串
你試過想過嗎? – Blorgbeard
「ab c」或「ab c」?有什麼區別.. –
@XiaoJia:ab和c之間的原始文本實際上有更多的空間,但它沒有顯示。 – nhahtdh