给定两个字符串,如果其中一个字符串出现在另一个字符串的最末尾,则返回 true,忽略大小写差异(换句话说,计算不应“区分大小写”)。注意: str.toLowerCase() 返回字符串的小写版本。
endOther("Hiabc", "abc") → 真
endOther("AbC", "HiaBc") → 真
endOther("abc", "abXabc") → 真
public class endOtherClass{
public static void main(String args[]) {
boolean is = endOther("yz","12xz") ;
System.out.println(is) ;
}
public static boolean endOther(String a, String b) {
a = a.toLowerCase() ;
b = b.toLowerCase() ;
if( a.length() == b.length()){
System.out.println("a and b have same length!") ;
if(a.equals(b)){
System.out.println("wow, even better - they are exact same") ;
return true ;
}
else {
System.out.println("but are diff!") ;
return false ;
}
}
String shorter = "" ;// figure out which - a or b - is shorter
String longer = "" ;// and which one is longer
if( a.length() > b.length() ){ shorter = b ; longer = a ;}
else { shorter = a ; longer = b ;}
int offset = longer.length() - shorter.length() ; // the offset is used to know where exactly to start comparing
//go through the shorter and compare the corresponding part of the longer string
for(int i = 0 ; i < shorter.length() ; i++){
System.out.println("comparing subs: " + shorter.substring(i,i+1) + " and " + longer.substring(offset+i, offset+i+1)) ;
if( !shorter.substring(i,i+1).equals( longer.substring(offset+i, offset+i+1) ) ){ //we add offset so we can start comparing the last n characters of shorter string!
System.out.println("something wrong in long: " + longer.substring(offset+i, offset+i+1)) ;
System.out.println("something wrong in short: " + shorter.substring(i,i+1)) ;
return false ;
}
}
return true ;
}
}
我 90% 确定这段代码可以简化,但我不知道其他逻辑或思考这个简单练习的方式
有人可以帮我重构它并使它更小吗?