力扣中【String类】相关的习题

目录

1.字符串中的第一个唯一字符

2.字符串最后一个单词的长度

3. 验证回文串


1.字符串中的第一个唯一字符

链接   387. 字符串​​​​​​中的第一个唯一字符

分析一下

上代码

class Solution {
    public int firstUniqChar(String s) {
        int[] count =new int[26]; 
        for(int i = 0; i < s.length(); i++) {
             char ch = s.charAt(i);
             count[ch - 'a'] ++;     
        }
       for(int i = 0; i < s.length(); i++) {
           char ch = s.charAt(i);
           if(count[ch - 'a'] == 1) {
               return i;
           }
       }
       return -1;
    }
}

2.字符串最后一个单词的长度

链接  字符串最后一个单词的长度_牛客题霸_牛客网 (nowcoder.com)

 分析一下

 上代码,第一种思路

import java.util.Scanner;
 
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while(in.hasNextLine()) {
            String str =  in.nextLine();
            int index = str.lastIndexOf(" ");
            String ret = str.substring(index+1);
            System.out.println(ret.length());
        }
    }
}

第二种思路

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
                Scanner in = new Scanner(System.in);
                String str =  in.nextLine();
                String[] strings = str.split(" ");
                System.out.println(strings[strings.length-1].length());
    }
}


3. 验证回文串

链接  125. 验证回文串

分析一下

 上代码

class Solution {
    
    private boolean isLegalChar(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;
        int right = s.length() - 1;
        while(left < right) {
            //从左边找到一个有效的字符
            while(left < right && !isLegalChar(s.charAt(left)) ){
                left++;
            }

            //从右边找到一个有效的字符
            while(left < right && !isLegalChar(s.charAt(right)) ) {
                right--;
            }
            
            //left和right 下标都是有效的字符,但是相不相同,不一定的
            if(s.charAt(left) != s.charAt(right)) {
                return false;
            }else {
                left++;
                right--;
            }
        }
        return true;
    }
}

猜你喜欢

转载自blog.csdn.net/m0_58761900/article/details/125032981