牛客網——華爲機試(題27:查找兄弟單詞)(Java)

題目描述:

輸入描述:

先輸入字典中單詞的個數,再輸入n個單詞作爲字典單詞。
輸入一個單詞,查找其在字典中兄弟單詞的個數
再輸入數字n

輸出描述:

根據輸入,輸出查找到的兄弟單詞的個數

示例1:

輸入:

3	abc	bca	cab	abc	1

輸出:

2	bca

代碼: 

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;

public class Main {
	public static void main ( String[] args ) throws IOException {
		BufferedReader bf = new BufferedReader( new InputStreamReader( System.in) );
		String s;
		while( ( s = bf.readLine() ) != null ) {
		String str[] = s.split("\\s+");
		String brother[] = new String[ str.length ];
		
		int n = Integer.parseInt(str[ 0 ]);
		String words = str[ n + 1 ];
		int k = Integer.parseInt( str[ str.length - 1 ] );
		
		int j = 0;
		for( int i = 1 ; i <= n ; i++ ) {
			if ( match( words , str[ i ] ) ) {
				brother[ j ] = str[ i ];
				j++;
			}
		}
		
		String a[] = new String[ j ];
		for ( int i = 0 ; i < j ; i++ ) {
			a[ i ] = brother[ i ];
		}

		
		if ( j == 0 ) {
			System.out.println( 0 );
		}
		else if ( k - 1 > j ) {
			System.out.println( j );
		}
		else {
			System.out.println( j );
			Arrays.sort( a );
			System.out.println( a[ k - 1 ] );
		}
		}
	}
	
	static boolean match( String s1 , String s2 ) {
		
		int a1[] = new int[ 26 ];
		int a2[] = new int[ 26 ];
		
		if ( !s1.equals( s2 ) ) {
			for ( int i = 0 ; i < 26 ; i++ ) {
				char c = (char) (i + 'a');
				for ( int j = 0 ; j < s1.length(); j++ ) {
					if ( c == s1.charAt( j ) ) {
						a1[ i ]++;
					}
				}
				for ( int k = 0 ; k < s2.length(); k++ ) {
					if ( c == s2.charAt( k ) ) {
						a2[ i ]++;
					}
				}
			}
			int judgement = 0;
			for ( int i = 0 ; i < 26 ; i++ ) {
				if ( a1[ i ] != a2[ i ] ) {
					judgement++;
				}
			}
			
			if ( judgement == 0 ) {
				return true;
			}
			else {
				return false;
			}
		}
		
		else {
			return false;
		}
	}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章