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的包装类的方法进行判断
-
相关阅读:
Python连接MYSQL、SQL Server、Oracle数据入库一网打尽
低代码平台在金融行业的OA解决方案
多标签分类损失函数/精度 BCEWithLogitsLoss MultiLabelSoftMarginLoss BCELoss
pygame制作游戏全套的
复习C部分:三大循环while篇(内含continue(常用场景2)和break(常用场景1)介绍和使用详情)
platformIO开发arduino
Docker - 发送 Container 日志到 AWS CloudWatch
使用VNC过程中遇到的问题总结
Redis之分布式锁
Java反序列化之CommonsCollections(CC1)分析篇
-
原文地址:https://blog.csdn.net/weixin_61436104/article/details/128096687