「お題:文字列を先頭から見て同じところまで除去」をJavaで挑戦してみた

お題:文字列を先頭から見て同じところまで除去 - No Programming, No Life

先にソートしたら楽じゃね?と思ったのでやってみた。

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Odai{
    
    public static List<String> hoge( final List<String> arg ){
        List<String> copy = new ArrayList<String>( arg );
        Collections.sort( copy );
        String first = copy.get( 0 );
        String last = copy.get( copy.size() - 1 );
        int length = first.length() < last.length() ? first.length() : last.length();
        int index = 0;
        while( index < length && first.charAt( index ) == last.charAt( index ) )index++;
        List<String> res = new ArrayList<String>(arg.size());
        for( String s : arg )res.add( s.substring( index ) );
        return res;    
    }
}

ふつうに書くとこう?

import java.util.ArrayList;
import java.util.List;

public class Odai{

    public static List<String> hoge( final List<String> arg ){
        int length = arg.get( 0 ).length();
        for( int i = 1; i < arg.size(); i++ ){
            length = length < arg.get( i ).length() ? length : arg.get( i ).length();
            int index = 0;
            for( ; index < length && arg.get( 0 ).charAt( index ) == arg.get( i ).charAt( index ); index++ ){}
            length = index;
        }
        List<String> res = new ArrayList<String>(arg.size());
        for( String s : arg )res.add( s.substring( length ) );
        return res; 
    }
}

テストコード

import java.util.Arrays;
import java.util.List;
import junit.framework.TestCase;

public class OdaiTest extends TestCase{
    
    public void testHoge(){
        List<String> res;
        res = Odai.hoge( Arrays.asList( "abcdef", "abc123" ) );
        
        assertEquals( "def", res.get( 0 ) );
        assertEquals( "123", res.get( 1 ) );
        
        res = Odai.hoge( Arrays.asList( "あいうえお", "あいさんさん", "あいどる" ) );
        
        assertEquals( "うえお", res.get( 0 ) );
        assertEquals( "さんさん", res.get( 1 ) );
        assertEquals( "どる", res.get( 2 ) );
        
        res = Odai.hoge( Arrays.asList( "12345", "67890", "12abc" ) );
        
        assertEquals( "12345", res.get( 0 ) );
        assertEquals( "67890", res.get( 1 ) );
        assertEquals( "12abc", res.get( 2 ) );
    }
}