題目:輸入兩個字符串,計算兩個字符串的最大公共字串的長度,并輸出,字符不區分大小寫
eg:輸入abcde xxxBcyyy,輸出 2。
完整Java代碼:
import java.util.*;public class Main { public static void main(String arg[]){ Scanner s=new Scanner(System.in); String str1=s.next(); String str2=s.next(); s.close(); String maxStr,minStr; if(str1.length()>str2.length()){ maxStr=str1; minStr=str2; } else{ maxStr=str2; minStr=str1; } int max=maxStr.length(); int min=minStr.length();//System.out.學習點一:利用Java標簽跳出多重循環;
學習點二:靈活使用String.regionMatches方法,來判斷兩個字符串的子串區域是否相等,具體可參考Java API文檔如下。
regionMatchespublic boolean regionMatches(booleanignoreCase, inttoffset, Stringother, intooffset, intlen)
- 測試兩個字符串區域是否相等。
將此String對象的子字符串與參數other的子字符串進行比較。如果這兩個子字符串表示相同的字符序列,則結果為true,當且僅當ignoreCase為 true 時忽略大小寫。要比較的此String對象的子字符串從索引toffset處開始,長度為len。要比較的other的子字符串從索引ooffset處開始,長度為len。當且僅當下列至少一項為 true 時,結果才為false:
- toffset為負。
- ooffset為負。
- toffset+len大于此String對象的長度。
- ooffset+len大于另一個參數的長度。
- ignoreCase為false,且存在某個小于len的非負整數k,即:
this.charAt(toffset+k) != other.charAt(ooffset+k)- ignoreCase為true,且存在某個小于len的非負整數k,即:
以及:Character.toLowerCase(this.charAt(toffset+k)) != Character.toLowerCase(other.charAt(ooffset+k))Character.toUpperCase(this.charAt(toffset+k)) != Character.toUpperCase(other.charAt(ooffset+k))
- 參數:
ignoreCase
- 如果為true
,則比較字符時忽略大小寫。toffset
- 此字符串中子區域的起始偏移量。other
- 字符串參數。toffset
- 字符串參數中子區域的起始偏移量。len
- 要比較的字符數。- 返回:
- 如果此字符串的指定子區域匹配字符串參數的指定子區域,則返回
true
;否則返回false
。是否完全匹配或考慮大小寫取決于ignoreCase
參數。
新聞熱點
疑難解答