2016-06-10 5 views
0

두 개의 String 개체를 허용하는 함수를 만들었습니다. 이 메서드는 두 문자열에만 나타나는 영문자가 나타날 때마다 요소 하나를 포함하는 문자 배열을 반환합니다. 어느 한 문자열의 알파벳이 아닌 문자는 무시됩니다. 모든문자열 구문 분석 및 비교

public static void main(String[] args) { 
    System.out.println(alphabetize("ABc","abC")); 
} 

static String alphabetize(String one, String two) {   
    String result = one + two; 
    String expression = "^[a-zA-Z]*$"; 
    CharSequence inputStr = result; 
    Pattern pattern = Pattern.compile(expression); 
    Matcher matcher = pattern.matcher(inputStr); 
    if(matcher.matches()) { 
     char[] chars = result.toCharArray(); 
     Set<Character> charSet = new LinkedHashSet<Character>(); 
     for (char c : chars) { 
      charSet.add(c); 
     } 
     StringBuilder sb = new StringBuilder(); 
     for (Character character : charSet) { 
      sb.append(character); 
     } 
     return (sb.toString());  
    } else { 
     return null; 
    }  
} 

먼저 어떻게 어떤 소문자 전에 나오는 모든 대문자로, 값 알파벳 순서가된다를 반환하는 방법으로 배열을 정렬 할 수 있습니다. 게다가, 케이스는 관련이 있고 고려되어야한다. 예를 들어, 제공된 문자열 "aBA"및 "abA"가있는 경우 함수는 두 번째 문자열에 대문자 B가 없기 때문에 { 'B', 'b'}로 구성된 배열을 반환해야하며 소문자 'b'는 첫 번째 문자열. 또한 여러 번 발생하는 것이 적절하므로 고려해야합니다. 예를 들어 제공된 문자열 "aba"및 "ba"가있는 경우 함수는 두 번째 문자열에 'a'문자가 한 번만 표시되므로 {a '}로 구성된 배열을 반환해야합니다.

예 :

enter image description here

사람이 문제 해결을 통해 나를 인도 할 수 있습니까? Java에서 저의 소수 경험은 저를 해결책으로 이끌지 않습니다.

+0

결과 배열이 { 'A', 'B', 'b'} (으)로 구성된 경우 원하는대로 정렬 하시겠습니까 아니면 { 'A', 'B' 'a', 'b'}? – Zircon

+1

코드를 형식화하는 데 많은 노력을 기울이십시오. –

+0

@ 존 키스 미안 존, 포맷되지 않았습니까? –

답변

0
public static void main(String[] args) 
{ 
    HashMap<Character, Integer> store = new HashMap<Character, Integer>(); 
    arrangeFrequency("ababaABABR", store); 
    arrangeFrequency("ababp", store); 

    Object[] output =store.keySet().toArray(); 
    Arrays.sort(output); 
    System.out.println(Arrays.toString(output)); 
} 

private static void arrangeFrequency(String str, HashMap<Character, Integer> s1) 
{ 
    int defaultVal = (s1.isEmpty()) ? 1: -1; 
    for(int i=0; i<str.length();i++) 
    { 
     char c = str.charAt(i); 
     if(Character.isLetter(c)) 
     { 
      int val = s1.containsKey(c) ? (s1.get(c).intValue()+defaultVal) : 1; 
      if(val>0) 
       s1.put(c, val); 
      else 
       s1.remove(c); 
     } 
    } 
} 
+0

고맙습니다. –

+0

경고 : 버그가 있습니다. 프로덕션에 보내기 전에 수정하십시오. 힌트 :''aa "'와''aaaa"'로 입력하십시오. – Azodious

+0

예, 그것을 깨닫고 그것을 이미 분류했습니다. 고맙습니다. –

0

첫 번째 문자열의 문자 수에 Map<Character, Integer>을 사용해보십시오. 그런 다음 두 번째 문자열의 문자를 반복하고지도에서 찾으면 숫자를 1 씩 줄입니다. 숫자가 0에 도달하면지도에서 문자를 찾지 못합니다.지도에서 문자를 찾지 못하면 문자를 목록 (또는 중복을 원하지 않으면 설정). 마지막에지도에 남아있는 모든 문자를 목록에 수집하고지도 값이 나타내는만큼 추가합니다. 마지막으로 필요에 따라 목록을 정렬하십시오.

예 :

String s1 = "xyyzaBC"; 
String s2 = "zyxBcA"; 

Map<Character, Integer> charCounts = new HashMap<>(); 

//Collect chars in s1 
for(char c: s1.toCharArray()) { 
    Integer count = charCounts.get(c); 
    if(count == null) { 
    count = 0; 
    } 
    count++; 
    charCounts.put(c, count); 
} 

//Check chars in s2 
List<Character> nonMatchingChars = new LinkedList<>(); 
for(char c: s2.toCharArray()) { 
    Integer count = charCounts.get(c); 

    if(count == null) { 
    //character not found 
    nonMatchingChars.add(c); 
    } else { 
    count--; 
    if(count <= 0) { 
     //count reduced to 0, remove now 
     charCounts.remove(c); 
    } else { 
     charCounts.put(c, count); 
    } 
    }   
} 

//Add chars still in the map 
for(Map.Entry<Character, Integer> e : charCounts.entrySet()) { 
    for(int i = 0; i < e.getValue(); i++) { 
    nonMatchingChars.add(e.getKey()); 
    } 
} 

//Sort 
Collections.sort(nonMatchingChars); 

System.out.println(nonMatchingChars); 

출력 : 이것은 당신이 시작하는 있지만 완전한 해결책이 될 의미되지 않는다는 것을 [A, C, a, c, y]

참고. 최소한 알파가 아닌 문자의 처리를 추가해야합니다.

+0

고맙습니다. –