Problem Statement
My solution
/**
* @(#)LetterInterchange.java
*
*
* @author foo bar
* @version 1.00 2007/9/4
*/
public class LetterInterchange
{
/**
* Method interchangeWhich
* @return
*
*/
public int [] interchangeWhich(String[] s1,String[] s2) {
int [] a = new int [ 2 ];
int small = 0 ; // 记录最小的index
int r = 0 ; // 第一个逆序出现的位置
boolean bReverse = false ; // 是否有逆序
String str = "" ;
// 连接字符串
for ( int i = 0 ; i < s1.length;i ++ )
str += s1[i];
for ( int i = 0 ; i < s2.length;i ++ )
str += s2[i];
// 寻找逆序位置
for ( int i = 1 ; i < str.length(); i ++ ){
if ( ! bReverse && str.charAt(i) < str.charAt(i - 1 ) ){
r = i - 1 ;
small = i;
bReverse = true ;
}
if ( str.charAt(i) < str.charAt(small))
small = i;
}
// 存在逆序
if (r > 0 ){
a[ 0 ] = str.indexOf(str.charAt(r));
a[ 1 ] = str.lastIndexOf(str.charAt(small));
return a;
}
// 不存在逆序
char first = str.charAt( 0 );
for ( int j = 1 ; j < str.length();j ++ ){
if ( str.charAt(j) != first){
first = str.charAt(j);
} else {
a[ 0 ] = j - 1 ;
a[ 1 ] = j;
return a;
}
}
// 不存在逆序并且没有相同字母
a[ 0 ] = str.length() - 2 ;
a[ 1 ] = str.length() - 1 ;
return a;
}
public static void main(String[] args)
{
LetterInterchange lic = new LetterInterchange();
String[] s1 = { " aaaaa " , " gggggg " };
String[] s2 = { " gggii " , " iiiiinnnnnn " , " nnnn " } ;
int [] a = lic.interchangeWhich(s1,s2);
System.out.println( " { " + a[ 0 ] + " , " + a[ 1 ] + " } " );
}
}
* @(#)LetterInterchange.java
*
*
* @author foo bar
* @version 1.00 2007/9/4
*/
public class LetterInterchange
{
/**
* Method interchangeWhich
* @return
*
*/
public int [] interchangeWhich(String[] s1,String[] s2) {
int [] a = new int [ 2 ];
int small = 0 ; // 记录最小的index
int r = 0 ; // 第一个逆序出现的位置
boolean bReverse = false ; // 是否有逆序
String str = "" ;
// 连接字符串
for ( int i = 0 ; i < s1.length;i ++ )
str += s1[i];
for ( int i = 0 ; i < s2.length;i ++ )
str += s2[i];
// 寻找逆序位置
for ( int i = 1 ; i < str.length(); i ++ ){
if ( ! bReverse && str.charAt(i) < str.charAt(i - 1 ) ){
r = i - 1 ;
small = i;
bReverse = true ;
}
if ( str.charAt(i) < str.charAt(small))
small = i;
}
// 存在逆序
if (r > 0 ){
a[ 0 ] = str.indexOf(str.charAt(r));
a[ 1 ] = str.lastIndexOf(str.charAt(small));
return a;
}
// 不存在逆序
char first = str.charAt( 0 );
for ( int j = 1 ; j < str.length();j ++ ){
if ( str.charAt(j) != first){
first = str.charAt(j);
} else {
a[ 0 ] = j - 1 ;
a[ 1 ] = j;
return a;
}
}
// 不存在逆序并且没有相同字母
a[ 0 ] = str.length() - 2 ;
a[ 1 ] = str.length() - 1 ;
return a;
}
public static void main(String[] args)
{
LetterInterchange lic = new LetterInterchange();
String[] s1 = { " aaaaa " , " gggggg " };
String[] s2 = { " gggii " , " iiiiinnnnnn " , " nnnn " } ;
int [] a = lic.interchangeWhich(s1,s2);
System.out.println( " { " + a[ 0 ] + " , " + a[ 1 ] + " } " );
}
}