1.. 第一个只出现一次的字符
- class Solution {
- public int firstUniqChar(String s) {
- int []count =new int[125];
- for(int i=0;i
- char ch=s.charAt(i);
- count[ch]++;
-
- }
-
- for(int i=0;i
- char ch = s.charAt(i);
- if (count[ch] == 1) {
- return i;
- }
- }
- return -1;
- }
- }

假设是这样一组字符串,返回第一个只出现一次的字符,那就是b,我们可以这样做
1.创建一个大的数组,用来记录每个字母出现的次数
2.再次遍历字符串,返回计数数组是1的字母的下标;
但是这样浪费的空间比较多,所以采取-97的做法,正好对应0,1,2,3等这样的位置
、
- class Solution {
- public int firstUniqChar(String s) {
- int []count =new int[125];
- for(int i=0;i
- char ch=s.charAt(i);
- count[ch-97]++;
-
- }
-
- for(int i=0;i
- char ch = s.charAt(i);
- if (count[ch-97] == 1) {
- return i;
- }
- }
- return -1;
- }
- }
2.求最后一个单词的长度
- import java.util.Scanner;
-
- // 注意类名必须为 Main, 不要有任何 package xxx 信息
- public class Main {
- public static void main(String[] args) {
- Scanner in = new Scanner(System.in);
- // 注意 hasNext 和 hasNextLine 的区别
- while (in.hasNextLine()) { // 注意 while 处理多个 case
- String str=in.nextLine();
- int index=str.lastIndexOf(" ");
- String ret=str.substring(index+1);
- int l=ret.length();
- System.out.println(l);
- }
- }
- }
这道题就用了String的库函数
3.判断是否为回文串
- class Solution {
- public boolean isPalindrome(String s) {
- s.toLowerCase();
- int left=0;
- int right=s.length()-1;
- while(left
- while(left
- left++;
- }
- while(left
- right--;
- }
-
- if(s.charAt(left)!=s.charAt(right)){
- return false;
- }else{
- left++;
- right--;
- }
- }
- return true;
-
- }
-
- private boolean isValidChar(char ch){
-
- if(Character.isDigit(ch)||Character.isLetter(ch)){
- return true;
- }
- return false;
- }
- }
这个题面试中常考,回文串就是正着写和倒着写是一样的,方法是这样的
先将所有字母变成小写,再看看是否符合数字或者字母,符合得话,左边往后走,右边往前走
然后判断左边和右边的是否相等,如果不相等,就返回FALSE,如果相等,就继续走
在判断字符是否合法时,可以使用char的包装类的方法进行判断
-
相关阅读:
JS调用PHP和PHP调用JS的方法
CSS样式中选择器+盒子模型+定位+浮动
MyBatisPlus详解(二)条件构造器Wrapper、自定义SQL、Service接口
使用jQuery的extend方法扩展window自定义对象
eclipse如何引入lombok插件
带你深入浅出Vue
基于深度学习视觉算法的多模型文件融合检测系统设计与实现及优化(工人姿态检测+安全帽佩戴检测系统)
CentOS7 Zookeeper3.8.3 单节点安装
SpringCache -- Redis --- 配置与缓存使用--配置过期时间
你真的会跟 ChatGPT 聊天吗?(下)
-
原文地址:https://blog.csdn.net/weixin_61436104/article/details/128096687