字符串问题之 找到被指定的新类型字符
类似于 Ab DC e
str="aaABCDEcBCg" k=7 Ec k=4 CD k=10 g
解题思路:
介绍一种最快最强的解题方法:
从 k-1 位置开始 向左统计连续出现的大写字母数量 int uNum 遇到小写字母就停止
如果 nNum为奇数, str[k..k+1]是被选中的新型字符
如果nNum为偶数,且 str[k]是大写字母,str[k..k+1]是被选中的新型字符
如果nNum为偶数,且srt[k]是小写字母,str[k]是被选中的新类型字符
package TT; public class Test6 { public static String pointNewchar(String s, int k){ if(s==null || s.equals("") || k<0 || k>=s.length()){ return ""; } char[] chas = s.toCharArray(); int uNum = 0; for(int i = k-1; i>=0; i--){ if( !isUpper(chas[i])){ break; } uNum++; } if((uNum &1) ==1){ //判断是否是奇数 return s.substring(k-1, k+1); } if(isUpper(chas[k])){ return s.substring(k, k+2); } return String.valueOf(chas[k]); } public static boolean isUpper(char a){ if(a >'A' && a<'Z'){ return true; }else{ return false; } } public static void main(String[] args){ String str = "aaABCDEcBcg"; int k = 7; String s = pointNewchar(str, k); System.out.println(s); } }
可以这么玩儿~
public class Test11 { public static int positionString(String str1, String str2) { String bigStr; String smallStr; int str1Length = str1.length(); int str2Length = str2.length(); if (str1Length >= str2Length) { bigStr = str1; smallStr = str2; } else { bigStr = str2; smallStr = str1; } int end = bigStr.length() - smallStr.length(); for (int i = 0; i <= end; i++) { char now = bigStr.charAt(i); int smallIndex = 0; int bigIndex = i; if (now == smallStr.charAt(smallIndex)) { while ((smallIndex < (smallStr.length() - 1)) && bigStr.charAt(++bigIndex) == smallStr.charAt(++smallIndex)) ; if (smallIndex == (smallStr.length() - 1)) { return i + 1; } } } return -1; } public static void main(String[] args) { String str1 = "aaABCDEcBCg"; String str2 = "g"; System.out.println(positionString(str1, str2)); } }