我一直在嘗試看看是否有辦法用雙回圈解決這個問題。回圈遍歷陣列中的每個單詞并檢查該單詞中是否存在提供的所有字符。
鍵盤壞了問題:
輸入 A = "你好,我親愛的朋友!"
輸入 B = ['h', 'e', 'l, 'o', 'm']
我們這里有一個損壞的鍵盤,其中只有串列 B 中的字母鍵(小寫和大寫)、數字鍵和標點符號鍵起作用。
撰寫接受字串 A 和字符 B 串列的函式,并回傳我們可以鍵入的單詞數。
解釋輸入:A“你好,我親愛的朋友!”,B = ['h', 'e', 'l, 'o', 'm'] 輸出:1
說明:對于第一個單詞“Hello”(包括逗號),我們可以找到串列 B 中的每個字符。由于所有標點鍵都可以正常作業,因此輸出 。
對于第二個單詞“my”,我們只能在串列 B 中找到字符 'm',因此我們無法輸入整個單詞。然后同樣,“親愛的”,找不到char 'd',所以繼續;“朋友!”,找不到字符'f',所以繼續;
這是我迄今為止嘗試過的,但我不能使用 String 的 .contain() 方法,因為它只接受一個字符序列而不是一個字符陣列。如何使用 JAVA 檢查字符陣列的每個單詞?
提前致謝,感謝任何支持。
public class BrokenKeyboard
{
public static void main(String[] args)
{
String stringText = "Hello my dear friend";
char [] charLetterArray = {'h', 'e', 'l', 'o', 'm'};
howManyWordsCalc(stringText, charLetterArray);
}
// Only words from stringText that can be typed in whole should be printed.
// If the letters present in the word aren't present in charLetterArray they don't get printed
public static int howManyWordsCalc(String text, char[] letters)
{
int wordCount = 0;
// sanitise input
if (text.isEmpty())
{
return 0;
}
else
{
text = text.toLowerCase();
String[] stringSeparated = text.split(" ");
for (int i = 0; i < stringSeparated.length; i )
{
System.out.println(stringSeparated[i]);
for (int j = 0; j < letters.length; j )
{
// stringSeparated[i].contains(letters)
if (stringSeparated[i].contains())
{
wordCount ;
}
}
}
return wordCount;
}
}
}
uj5u.com熱心網友回復:
這是一個示例解決方案:
public class Main{
public static void main(String[] args){
String stringText = "Hello my dear friend";
char [] charLetterArray = {'h', 'e', 'l', 'o', 'm'};
System.out.println(howManyWordsCalc(stringText, charLetterArray));
}
// Only words from stringText that can be typed in whole should be printed.
// If the letters present in the word aren't present in charLetterArray they don't get printed
public static int howManyWordsCalc(String text, char[] letters){
int wordCount = 0;
// sanitise input
if (text.isEmpty()){
return 0;
}
else{
text = text.toLowerCase();
String[] stringSeparated = text.split(" ");
for (int i = 0; i < stringSeparated.length; i ){
int validLetters = 0;
for(int j = 0; j < stringSeparated[i].length(); j ){
for(char c: letters){
if(c == stringSeparated[i].charAt(j)){
validLetters ;
break;
}
}
}
if(validLetters == stringSeparated[i].length()){
wordCount ;
}
}
return wordCount;
}
}
}
這段代碼的作業方式與您的完全相同,只是檢查單詞是否可以由可用字母組成的演算法。
我首先遍歷陣列中每個單詞的演算法。然后,我創建了一個名為 validLetters 的整數,我們將在其中檢查我們可以鍵入的單詞中有多少個字母。如果 validLetters 的數量等于單詞的長度,則可以鍵入該單詞。
為了檢查一個字母是否可以輸入,我們將遍歷單詞中的每個字母,看看它是否在陣列字母之內。如果是,我們增加我們的 validLetters 并退出回圈。
或者,如果您想在兩個 for 回圈中嚴格執行此操作,這是一個縮短版本:
import java.util.*;
public class Main{
public static void main(String[] args){
String stringText = "Hello my dear friend";
char [] charLetterArray = {'h', 'e', 'l', 'o', 'm'};
System.out.println(howManyWordsCalc(stringText, charLetterArray));
}
// Only words from stringText that can be typed in whole should be printed.
// If the letters present in the word aren't present in charLetterArray they don't get printed
public static int howManyWordsCalc(String text, char[] letters){
int wordCount = 0;
// sanitise input
if (text.isEmpty()){
return 0;
}
else{
text = text.toLowerCase();
String[] stringSeparated = text.split(" ");
for (int i = 0; i < stringSeparated.length; i ){
int validLetters = 0;
for(int j = 0; j < stringSeparated[i].length(); j ){
if (new String(letters).indexOf(stringSeparated[i].charAt(j)) != -1) {
validLetters ;
}
}
if(validLetters == stringSeparated[i].length()){
wordCount ;
}
}
return wordCount;
}
}
}
如果您有任何問題/澄清,請告訴我!
uj5u.com熱心網友回復:
我稍微改了一下,看看:
public static void wordCalc(String input, char[] chars) {
String[] inputWords = input.toLowerCase().split(" ");
boolean[] allLetters = new boolean[26];
for(int i=0; i<chars.length; i ) {
allLetters[chars[i] - 'a'] = true;
}
int wordCount = 0;
for(String word : inputWords) {
boolean isWordPossible = true;
for(int i=0; i<word.length(); i ){
if(!allLetters[word.charAt(i) - 'a']){
isWordPossible = false;
break;
}
}
if(isWordPossible) {
System.out.println("word " word " is possible");
wordCount ;
}
}
System.out.println(wordCount);
}
我曾經在互聯網上發現了這個非常巧妙的技巧。將允許的字母存盤在布爾陣列中。這樣,當您想檢查是否char允許 a 時,您只需檢查與該字符對應的索引處的陣列值即可!
然而,這確實讓我注意到了一個重要的問題。字符存盤為整數,這就是為什么你可以來回轉換它們并做一些時髦的事情,比如word.charAt(i) - 'a'(這會給你在布爾陣列中的位置,因為它會給你字母“a”和任何字母之間的距離在單詞中定位“i”)。
字串最終是字符陣列。所以你可以這樣做:
char[] stuff = someString.toCharArray();
同樣重要的是要注意字串是不可變的,并且字串字面量指向同一個物件。
關于時間復雜度的最后說明,最好盡可能避免嵌套回圈。如果你有大量的輸入,它會變得非常慢!如果你有一個回圈,它是 O(n) 時間,2 個回圈它已經是 O(n^2),就時間復雜度而言,這是相當慢的。但是,對于這種情況,我想不出不同的方法。您使用的結構和訪問方法會極大地影響性能。我認為您會非常喜歡HashSets,尤其是對于允許字符是唯一的這個問題。
uj5u.com熱心網友回復:
您可以使用另一個回圈(實際上與 具有相同的復雜性)來檢查單詞中的所有字符是否都包含在letters字符陣列中String::contains。
另外,我建議通過使用[\p{Z}\p{P}] 正則運算式拆分重復的標點符號和/或空格字符來獲取單詞,其中\p{Z}代表空格和\p{P}標點符號。
public static int howManyWordsCalc(String text, char[] letters) {
int wordCount = 0;
String[] words = text.toLowerCase().split("[\\p{P}\\p{Z}] ");
for (String word : words) {
// System.out.print("'" word "'\t");
boolean allFound = true;
for (char c : word.toCharArray()) {
boolean found = false;
for (char letter : letters) {
if (c == letter) {
found = true;
break;
}
}
if (!found) {
// System.out.println("not found letter: " c " in word " word);
allFound = false;
break;
}
}
if (allFound) {
wordCount ;
// System.out.println("all found");
}
}
return wordCount;
}
測驗:
System.out.println(howManyWordsCalc(
"Hello, my dear friend!", new char[] {'h', 'e', 'l', 'o', 'm', 'y'}
));
輸出(啟用除錯列印):
'hello' all found
'my' all found
'dear' not found letter: d in word dear
'friend' not found letter: f in word friend
2
uj5u.com熱心網友回復:
我在 c# 中嘗試過相同的方法,但您也可以使用 HashSet 集合并嘗試相同的方法。Java HashSet 也有Contains()。
我希望這會有所幫助。
class Program
{
static void Main(string[] args)
{
string a = "Hello, my dear friend!";
string A = a.ToUpper();
string[] seperate = A.Split(new Char[] { ' ', ',', '.', '-', '\n', '\t', '!' });
HashSet<Char> hash = new HashSet<char>();
hash.Add('H');
hash.Add('E');
hash.Add('L');
hash.Add('O');
hash.Add('M');
int count = 0;
bool flag = true;
foreach (var w in seperate)
{
if (w.Length > 0) {
Char[] ca = w.ToCharArray();
foreach (var d in ca)
{
if(!hash.Contains(d))
{
flag = false;
break;
}
}
if(flag)
{
flag = true;
count ;
}
}
}
Console.WriteLine("Count : " count);
Console.Read();
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/381630.html
