Topcoder problem - LetterInterchange

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 ] + " } " );
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值