2012-12-10 2 views
0

과제에 대해 문장에서 재귀를 사용하여 가장 긴 단어를 찾아야합니다. 저는 문장의 처음 두 단어를 취하여 비교 한 다음 두 문장 중 더 긴 단어를 취해 나머지 문장의 다음 단어와 비교하는 방법을 썼습니다. 내 논리가 체크 아웃하지만 메서드가 올바르게 작동하지 않습니다. 공백을 제거하는 우연이 있다고 생각합니다. 이것이 작동하지 않는 이유입니다.재귀를 사용하여 문장에서 가장 긴 단어 찾기 (Java)

public static String longestWord(String sentence) 
{ 
    if (sentence.indexOf(' ') == -1) {  // IF sentence only has one word 
     return sentence; 
    } 

    String word1 =(sentence.indexOf(" ") != -1)? sentence.substring(0, sentence.indexOf(" ")): 
                sentence.substring(0); 
    String temp = sentence.substring(sentence.indexOf(" ")+1); 


    String word2 = null; 
    String rest = null; 
    if (sentence.indexOf(" ") != -1) { 
    word2 = (temp.indexOf(" ") != -1)? temp.substring(0, temp.indexOf(" ")+1): 
              temp.substring(0); 
    rest = temp.substring(temp.indexOf(" ")+1); 
    } 


    if (word1.length() > word2.length()) { 
     return longestWord(word1 + rest); 

    } 

    if (word2.length() > word1.length()) { 
     return longestWord(word2 + rest); 

    } 

    return sentence; 


} 
+0

당신은'같이 IndexOf ('')'와'같이 IndexOf를 ("")를 호출'; 그게 의도적 인거야? 첫 번째 테스트가 통과하면 어떤 상황에서 두 번째 테스트가 실패 할 수 있습니까? –

+0

"제대로 작동하지 않는다"고하면 무슨 뜻입니까? 샘플 입출력을 제공하면 도움이 될 것입니다. – Jeff

+0

@ Jeff 입력 : 가장 긴 단어는 수박입니다. 산출 : watermelonwatermelon – biohax2015

답변

1

당신은 몇있어 문제는 여기에 있지만, 나는 당신을 잡으려고하는 사람이 처음에 공간이 없도록 rest을 설정하고 있다고 생각하지만, 그 다음에는 단어의 시작 부분에 단어를 연결하는 것입니다. 그래서 "빠른 갈색 여우"-> "quickbrown fox".

두 단어의 길이가 같으면 전체 문장을 반환합니다. 대신 if 문장을 else 문장으로 만들고 마지막 return 문을 제거해야합니다.

EDIT : 초점을 되돌릴 경우 재귀 솔루션을 더 간단하게 찾을 수 있습니다. 매번 처음 두 단어를 사용하는 대신 첫 번째 단어를 나머지 단어 중 가장 긴 단어와 비교하십시오.

longestWord(String sentence) { 
    if (sentence.indexOf(' ') == -1) {  // IF sentence only has one word 
     return sentence; 
    } 
    String firstWord = getFirstWord(sentence);//how you're doing it now 
    String rest = getRest(sentence);//Just the sentence without the first word (and first space...) 
    String secondWord = longestWord(rest); 
    return firstWord.length >= secondWord.length ? firstWord : secondWord; 
} 
1

반복적으로 그것을 할 수있는 간단한 방법이있다는 : 단어로 문자열을 분리, 다음과 같이,이 방법의 재귀 호출을 수행

string longest(string sentence) { 
    return longestRecursive(sentence.Split(' '), 0, ""); 
} 

string longestRecursive(string[] words, int index, string longestSoFar) { 
    // This should be very easy to implement: 
    // If index == words.Length, longestSoFar is your answer 
    // Check words[0] against longestSoFar, and make a recursive invocation 
} 
0

문장이 String 인 경우.

String.Split ("");

문자열 배열에 결과를 저장하십시오.

재귀를 사용하면 .length를 사용하여 가장 긴 문자열을 찾을 수 있습니다.

0

나는 꼬리를 호출 최적화를하지 않습니다

public static String longestWord(String sentence) { 
     return longestWord(sentence, ""); 
    } 

    private static String longestWord(String sentence, String longestWord) { 
     int i = sentence.indexOf(' '); 
     if (i == -1) { 
      return sentence.length() > longestWord.length() ? sentence : longestWord; 
     } 
     longestWord = i > longestWord.length() ? sentence.substring(0, i) : longestWord; 
     sentence = sentence.substring(i + 1); 
     return longestWord(sentence, longestWord); 
    } 
0

자바로 할 것, 그래서 이것은 쉽게 스택을 날려 버릴 수 있습니다. 그러나 재귀 적으로 (그리고 TCO를 가진 언어로, 스택 중립적 인) 요청했습니다. 단일 문자열 만 생성한다는 점에 유의하십시오.

public static String longestWord(String sentence) { 
    return longestWordHelper(sentence, 0, 0, 0, 0); 
} 

String longestWordHelper(String sentence, 
         int best_len, int best_end, 
         int cur_len, int cur) { 
    if (cur == sentence.length()) 
    if (cur_len > best_len) 
     return sentence.substring(cur_end - cur_len, cur_len); 
    else 
     return sentence.substring(best_end - best_len, best_len); 
    if (isSpace(sentence.charAt(cur))) 
    if (cur_len > best_len) 
     return longestWordHelper(sentence, cur_len, cur, 0, cur + 1); 
    else 
     return longestWordHelper(sentence, best_len, best_end, 0, cur + 1); 
    else 
    return longestWordHelper(sentence, best_len, best_end, cur_len + 1, cur + 1); 
} 
0
package MujeebWorkspace.sampleprograms; 

class javaMujeeb{  
static String actualstring= "Today is a very good day"; 
static String[] splitstring = actualstring.split(" "); 

public static void main(String [] args){ 
    LongWord(); 
    ShortWord(); } 

public static void LongWord() {  
    String longword = ""; 
    for (int i=0; i<=splitstring.length-1; i++){  
    if (longword.length()<splitstring[i].length()) 
     longword = splitstring[i]; } 
    System.out.println(longword); } 

    public static void ShortWord(){ 
     String shortword = " "; 
     for (int i=0; i<=splitstring.length-1; i++){   
     if (splitstring[i].length()<shortword.length()) 
      shortword = splitstring[i];   }  
     System.out.println(shortword);  } 

}

관련 문제