1.一个字符串最后一个单词的长度(字符串单词之间为空格,结尾不为空格)
//最后一个单词的长度
//方法1
public static void main1(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNext()) { // 注意 while 处理多个 case
String str = in.nextLine();
int index = str.lastIndexOf(" ");
int len = str.length()-index-1;
System.out.println(len);
}
}
//方法2
public static void main2(String[] args) {
Scanner in = new Scanner(System.in);
// 注意 hasNext 和 hasNextLine 的区别
while (in.hasNext()) { // 注意 while 处理多个 case
String str = in.nextLine();
String[] strs = str.split(" ");
String str1 = new String("");
for(int i = 0;i<strs.length;i++){
if(i==strs.length-1){
str1 += strs[i];
}
}
System.out.println(str1.length());
}
2.字符串中首个出现一次的字母
//首个出现一次的字母
public int firstUniqChar(String s) {
int[] count = new int[256];
// 统计每个字符出现的次数
for(int i = 0; i < s.length(); ++i){
count[s.charAt(i)]++;
}
// 找第一个只出现一次的字符
for(int i = 0; i < s.length(); ++i){
if(1 == count[s.charAt(i)]){
return i;
}
}return -1;
}
3.字符串是否为回文
//回文检查
public static boolean isValidChar(char ch){
if((ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9')){
return true;
}
return false;
}
public boolean isPalindrome(String s) {
// 将大小写统一起来
s = s.toLowerCase();
int left = 0, right = s.length()-1;
while(left < right){
// 1. 从左侧找到一个有效的字符
while(left < right && !isValidChar(s.charAt(left))){
left++;
}
// 2. 从右侧找一个有效的字符
while(left < right && !isValidChar(s.charAt(right))){
right--;
}
if(s.charAt(left) != s.charAt(right)){
return false;
}else{
left++;
right--;
}
}
return true;
}