2012-10-14 3 views
3

문자열 목록이 있고 각 문자열에 대해 다른 모든 문자열과 비교하여 모든 문자가 하나만 제외하고 동일한지 확인하고 싶습니다. 예를 진정한 잠금에 대해문자열이 다른 문자 중 하나를 제외한 모든 문자와 일치하는지 확인합니다.

바위를 체크 할 것

시계를 반환하고 무리 것이다 수표를 들어

는 더 이상 더 적은 다른없는 한 문자가 있습니다.

진창에 대한 바위는 분명히 false를 반환합니다.

나는 목록을 처음으로 루핑하고 두 번째 루프에 대해 첫 번째 문자열을 검사하기 위해 두 번째 루프를 갖는 것에 대해 생각 해왔다.

그리고 나서 split("");을 사용하여 각 문자열의 문자를 포함하는 두 개의 배열을 만든 다음 서로에 대해 배열 요소를 확인합니다 (즉, 각 배열을 다른 배열의 동일한 위치와 비교 함 1-1 2-2 등 ...).) 하나의 문자 비교 만 실패하면 두 문자열의 검사가 참입니다.

어쨌든 나는 많은 문자열 (4029)을 가지고 있으며, 순간적으로 구현하려고 생각하고있는 것을 고려할 때 큐빅 루프 (?)를 초래할 다른 루프 내에서 각각 3 개의 루프가 포함될 것이라고 생각하면 오랜 시간이 걸릴 것입니다 그 많은 요소들이 그럴 것입니까?

더 쉬운 방법이 있나요? 아니면이 방법은 실제로 작동합니까? 또는, 잘하면 안되지 만, 내가 제안한 해결책에 잠재적 인 논리적 결함이 있습니까?

고마워요!

답변

5

왜 순진한 방식으로하지 않습니까?

bool matchesAlmost(String str1, String str2) { 
    if (str1.length != str2.length) 
     return false; 
    int same = 0; 
    for (int i = 0; i < str1.length; ++i) { 
     if (str1.charAt(i) == str2.charAt(i)) 
      same++; 
    } 
    return same == str1.length - 1; 
} 

이제 2 진 알고리즘을 사용하여 모든 문자열을 서로 비교할 수 있습니다. 두 문자열의 길이를 가정

+0

건배, 나는이 방법을 많이 :) – DanMc

0

동일

String str1 = "rock"; 
     String str2 = "lick"; 

     if(str1.length() != str2.length()) 
      System.out.println("failed"); 

     else{ 
      if(str2.contains(str1.substring(0, str1.length()-1)) || str2.contains( str1.substring(1, str1.length()))){ 
       System.out.println("Success "); 
      } 

      else{ 
       System.out.println("Failed"); 
      } 
     } 
+0

무엇 rock'과''에 대한 좋아 릭'? –

+0

! 나는 그 테스트 케이스를 가져 가지 않았다. 위의 하나가 좋다 !! 이렇게 돼서 미안하다! – madhairsilence

0

이 가장 좋은 방법이 있지만 두 문자열이 같은 길이 아닌 경우이 하나도 작동하는지 확실하지. 예를 들면 다음과 같습니다. cat & cattp 한 문자 p가 다르며 t가 반복됩니다. hashmap & 문자 배열을위한 추가 공간을 사용하는 O (n) 시간 솔루션처럼 보입니다.

/** 
* Returns true if two strings differ by one character 
* @param s1 input string1 
* @param s2 input string2 
* @return true if strings differ by one character 
*/ 
boolean checkIfTwoStringDifferByOne(String s1, String s2) { 
    char[] c1, c2; 

    if(s1.length() < s2.length()){ 
     c1 = s1.toCharArray(); 
     c2 = s2.toCharArray(); 
    }else{ 
     c1 = s2.toCharArray(); 
     c2 = s1.toCharArray(); 
    } 

    HashSet<Character> hs = new HashSet<Character>(); 

    for (int i = 0; i < c1.length; i++) { 
     hs.add(c1[i]); 
    } 
    int count = 0; 
    for (int j = 0; j < c2.length; j++) { 
     if (! hs.contains(c2[j])) { 
      count = count +1; 
     } 
    } 

    if(count == 1) 
     return true; 
    return false; 
} 
0
Best way is to concatenate strings together one forward and other one in reverse order. Then check in single loop for both ends matching chars and also start from middle towards ends matching char. If more than 2 chars mismatch break. 
If one mismatch stop and wait for the next one to complete if it reaches the same position then it matches otherwise just return false. 

    public static void main(String[] args) { 

     // TODO code application logic here 
     New1 x = new New1(); 
     x.setFunc(); 
     } 

     static void setFunc(){ 
      Set s   = new HashSet<Character>(); 
      String input = " aecd"; 
      String input2 = "abcd"; 
      String input3 = new StringBuilder(input2).reverse().toString(); 
      String input4 = input.concat(input3); 
      int length = input4.length(); 

      System.out.println(input4); 
      int flag  = 0; 

      for(int i=1,j=length-1;j>i-1; i++,j--){ 

      if(input4.charAt(i)!=input4.charAt(j)){ 

       System.out.println(input4.charAt(i)+" doesnt match with "+input4.charAt(j)); 
        if(input4.charAt(i+1)!=input4.charAt(j)){ 
         System.out.println(input4.charAt(i+1)+" doesnt match with "+input4.charAt(j)); 
         flag = 1; 
         continue; 
        } else if(input4.charAt(i)!=input4.charAt(j-1)){ 
         System.out.println(input4.charAt(i)+" doesnt match with "+input4.charAt(j-1)); 
         flag = 1; 
         break; 
        } else if(input4.charAt(i+1)!=input4.charAt(j-1) && i+1 <= j-1){ 
         System.out.println(input4.charAt(i+1)+" doesnt match with xxx "+input4.charAt(j-1)); 
         flag = 1; 
         break; 
        } 
        } else { 
         continue; 
        } 
      } 

       if(flag==0){ 
        System.out.println("Strings differ by one place"); 
       } else { 
        System.out.println("Strings does not match"); 
       } 
     } 
0

모든 문자열이 동일한 길이를 가지고 있다고 가정하면,이 도움이 될 생각 :

public boolean differByOne(String source, String destination) 
{ 
    int difference = 0; 

    for(int i=0;i<source.length();i++) 
    { 
     if(source.charAt(i)!=destination.charAt(i)) 
     { 
      difference++; 

      if(difference>1) 
      { 
       return false; 
      } 
     } 
    } 

    return difference == 1; 
} 
관련 문제