2012-09-27 3 views
3

여기에 메서드 lastIndexOf이 있고, ch은 일치하는 문자이고 str은 소스 문자열입니다.자바 재귀는 문자열의 문자의 마지막 색인을 찾습니다.

public static int lastIndexOf(char ch, String str) { 
    // check for null string or empty string 
    if (str.length() == 0 || str == null) { 
     return -1; 
    } 

    int indexInRest = lastIndexOf(ch, str.substring(1)); 
    char first = str.charAt(0); 

    // recursive call to find the last matching character 
    if (first == ch) { 
     return 1 + indexInRest; // this might not work properly 
    } else 
     return indexInRest; 
} 

내 클래스의 주요 방법은 내가 호출하는 경우 :

System.out.println(lastIndexOf('r', "recurse")); 
    System.out.println(lastIndexOf('p', "recurse")); 

는 내가 가진 :

1 
-1 

원하는 결과는 다음과 같습니다

4 
-1 

제안하시기 바랍니다.

str.lastIndexOf(ch) 
+0

이 숙제가 있습니다 .. 기능 접근 방식을 복용에 대해? – user1329572

+1

및 기존 방법의 문제점 http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#lastIndexOf%28int%29? –

+0

네, 제안이 필요합니다. – Hank

답변

3

어떻게

public static int lastIndexOf(char ch, String str) { 
    if (str.charAt(str.length() - 1) == ch) { return str.length() -1; } 
    if (str.length() <= 1) { return -1; } 
    return lastIndexOf(ch, str.substring(0, str.length() - 1)); 
} 
+0

그것이 내가 필요한 것입니다. Johan에게 감사드립니다. – Hank

0

왜 이런 String.lastIndexOf를 사용 문자 배열

public static int lastIndexOf(char ch, String str, int deep) { 

그리고 증가하십시오 NPE가 strnull

이 같은 코드에 deep paramater를 추가하는 경우 올릴 수 있기 때문에

if (str == null || str.length() == 0) { 

:

+5

숙제이고 선생님이이 바퀴를 재발 명해 달라는 요청을했기 때문일 가능성이 큽니다. –

0

를 사용하여 일반적인 지침으로 String#lastIndexOf(int ch) 구현,

public int lastIndexOf(int ch) { 
    return lastIndexOf(ch, value.length - 1); 
} 

public int lastIndexOf(int ch, int fromIndex) { 
    if (ch < Character.MIN_SUPPLEMENTARY_CODE_POINT) { 
     // handle most cases here (ch is a BMP code point or a 
     // negative value (invalid code point)) 
     final char[] value = this.value; 
     int i = Math.min(fromIndex, value.length - 1); 
     for (; i >= 0; i--) { 
      if (value[i] == ch) { 
       return i; 
      } 
     } 
     return -1; 
    } else { 
     return lastIndexOfSupplementary(ch, fromIndex); 
    } 
} 

private int lastIndexOfSupplementary(int ch, int fromIndex) { 
    if (Character.isValidCodePoint(ch)) { 
     final char[] value = this.value; 
     char hi = Character.highSurrogate(ch); 
     char lo = Character.lowSurrogate(ch); 
     int i = Math.min(fromIndex, value.length - 2); 
     for (; i >= 0; i--) { 
      if (value[i] == hi && value[i + 1] == lo) { 
       return i; 
      } 
     } 
    } 
    return -1; 
} 

그리고이,

lastIndexOf(ch, value.length - 1); 

value이 같은 목표 문자열입니다

+0

자바는 반복 접근법을 사용한다는 점에 유의해야한다. 재귀 접근법으로 변환해야한다. – user1329572

0

첫째, 당신은 변경해야 재귀 호출 할 때마다 그 값

int indexInRest = lastIndexOf(ch, str.substring(1), deep++); 

다음, 반환 문장에서, 반환 된 값에 깊은 추가

return 1 + indexInRest + deep; // this might not work properly 

전화 기능 deep = 0, 또는 더 나은 아직 함께 처음의 3 개 개의 매개 변수 버전을 호출 lastIndexOf 두 개의 매개 변수 방법을 lastIndexOfdeep 매개 변수가 0으로 설정되어 있습니다.

3

String.lastIndexOf()가 API에 있으므로이 방법을 쓰지 않아도됩니다. 재귀를 사용하면 속도가 느려지고 많은 기억.

여기에 힌트가 있습니다. 지금 당신의 알고리즘은 문자를 앞에서 자르고 (substring (1)) 그들을 비교하는 것입니다. lastIndexOf()는 문자열의 뒤에서 일치하는 문자열을 찾은 다음 문자열을 찾으면 종료합니다.

0

당신은 또한 당신의 숙제로 요청 문자열 분석의 진화를 예측하기 위해 Matcher를 사용할 수 있습니다

public int getlastMatch(String searchPattern,String textString) { 
     int index = -1; 
     Pattern pattern = Pattern.compile(searchPattern); 
     Matcher matcher = pattern.matcher(textString); 

     while(matcher.find()) { 
       index = matcher.start(); 
     } 
     return index; 
    } 

textString는 우려 문자 될 수있다.

따라서 문자열 내에서 문자열의 마지막 부분을 반환합니다.

관련 문제