LeetCode——字符串

字符串

String
一、常用方法

String str = "adsfaxsdfas沙发上案发地方";

s.length() 获取字符串长度 18
s.charAt(int index):获取指定索引的字符
s.indexOf(String str): 获取str字符串对象中第一次出现的索引
s.substring(int start):从start开始截取字符串
s.substring(int start,int end):从start开始,到end结束截取字符串。包括start,不包括end
s.equals(obj) :比较字符串内容是否相同
s.equalsIgnoreCase(String anotherString):比较字符串的内容是否相同,忽略大小写
s.contains(CharSequence s):查看字符串中是都含有指定字符
s.split():分割字符串中指定的的字符,然后返回一个新的字符串
s.trim()去除字符串两端空格
s.concat(String str):在原有的字符串的基础上加上指定字符串

s.reverse()
s.toLowerCase():把字符串转换为小写字符串
s.toUpperCase():把字符串转换为大写字符串

一、最后一个单词的长度(58 )字符串遍历

完整过程为从后过滤掉空格找到单词尾部,
从尾部向前遍历,找到单词头部,
最后两者相减,即为单词的长度
时间复杂度:O(n),n为结尾空格和结尾单词总体长度

时间复杂度:O(m+n),m为字符串 s 的长度,n为字符串t的长度

class Solution {
    public int lengthOfLastWord(String s) {
      if(s == null || s.length() == 0) return 0;//边界值
      int count = 0;                           //计数器
      for(int i = s.length()-1; i >= 0; i--){
         if(s.charAt(i) == ' '){
           if(count == 0) continue;   //判断空格就停止计数
                break;
            }
            count++;
        }
        return count;        
    }
}

二、无重复字符的最长子串(3)滑动窗口

讲解地址
输入: “abcabcbb”
输出: 3
解释: 因为无重复字符的最长子串是 “abc”,所以其长度为 3。
思路:滑动窗口
定义一个 map 数据结构存储 (k, v),其中 key 值为字符,value 值为字符位置 +1,加 1 表示从字符位置后一个才开始不重复
在这里插入图片描述

import java.util.HashMap;
import java.util.Map;
public class Problems3 {
    public static void main(String[] args){
        lengthOfLongestSubstring("dppppp");
    }
   public  static int lengthOfLongestSubstring(String s){
        int n=s.length();  int ans =0;              //字符串长度与初始化返回值
       Map<Character,Integer> map =new HashMap<>();
       for(int start=0 ,end=0; end<n;end++){
           char aend = s.charAt(end);        //取出字符串中字符
           if(map.containsKey(end)){
                start=Math.max(start,map.get(aend));
           }else{
               ans=Math.max(ans,end-start+1);
               map.put(s.charAt(end),end+1);
           }
       }
       return ans;
   }
}

在这里插入图片描述

三、找不同(389)

给定两个字符串 s 和 t,它们只包含小写字母。
字符串 t 由字符串 s 随机重排,然后在随机位置添加一个字母。
请找出在 t 中被添加的字母
输入:
s = “abcd”
t = “abcde”
输出:e

public char findTheDifference(String s, String t) {
     char ans = t.charAt(t.length()-1);
       for(int i = 0; i < s.length(); i++) {
            ans ^= s.charAt(i);
            ans ^= t.charAt(i);
            }
            return ans;
 }

四、验证IP地址(468)

IPv4 地址由十进制数和点来表示,每个地址包含4个十进制数,其范围为 0 - 255, 用(".")分割。比如,172.16.254.1;
IPv6 地址由8组16进制的数字来表示,每组表示 16 比特。这些组数字通过 (":")分割。比如, 2001:0db8:85a3:0000:0000:8a2e:0370:7334 是一个有效的地址。

package 刷题;

public class IP_adress {
    public static void main(String[] args) {
        validIPAddress("123.230.11.255");
    }

    public static String  validateIPv4(String IP){
        String [] nums = IP.split("\\.",-1);
        for(String x:nums) {
            // Validate integer in range (0, 255):
            if(x.length()==0||x.length()>3)            return "Neither";// 1. length of chunk is between 1 and 3
            if (x.charAt(0) == '0' && x.length() != 1) return "Neither";// 2. no extra leading zeros
             // 3. only digits are allowed
            for(char ch :x.toCharArray()){
                if (! Character.isDigit(ch)) return "Neither";
            }// 4. less than 255
            if(Integer.parseInt(x)>255)   return"Neither";
            }
        return "IPv4";
        }
    public static String validateIPv6(String IP){
        String [] nums =IP.split(":",-1);
        String hexdigits = "0123456789abcdefABCDEF";
        for (String x : nums) {
            // Validate hexadecimal in range (0, 2**16):
            // 1. at least one and not more than 4 hexdigits in one chunk
            if (x.length() == 0 || x.length() > 4) return "Neither";
            // 2. only hexdigits are allowed: 0-9, a-f, A-F
            for (Character ch : x.toCharArray()) {
                if (hexdigits.indexOf(ch) == -1) return "Neither";
            }
        }
        return "IPv6";
    }
    public static String validIPAddress(String IP) {
        if (IP.chars().filter(ch -> ch == '.').count() == 3) {
            return validateIPv4(IP);
        }
        else if (IP.chars().filter(ch -> ch == ':').count() == 7) {
            return validateIPv6(IP);
        }
        else return "Neither";
    }
}

五、替换空格

空格替换成%20
输入:s = “We are happy.” 输出:“We%20are%20happy.”

class Solution {
    public String replaceSpace(String s) {
      StringBuilder str = new StringBuilder();
      for(Character c: s.toCharArray()){
            if(c ==' '){
            str.append("%20");
            }
            else str.append(c);
      }
      return str.toString();
    }
}

六、找出一个字母的字符(字节)

给出一个字符串,每个字母都连续出现了2次,且这2次是相邻的,只有1个字母出现了1次

public int findOdd(String str){
        int length = str.length();
        if (length == 1){      //长度为1,直接return
            return 0;
        }
        for (int i = 0; i + 1< length; i += 2) {
            if (str.charAt(i) != str.charAt(i+1)){
                return i;
            }
        }
        return length - 1;
    }

七、最长公共前缀(14)

标签:链表
当字符串数组长度为 0 时则公共前缀为空,直接返回
令最长公共前缀 ans 的值为第一个字符串,进行初始化
遍历后面的字符串,依次将其与 ans 进行比较,两两找出公共前缀,最终结果即为最长公共前缀 如果查找过程中出现了 ans为空的情况,则公共前缀不存在直接返回
时间复杂度: O(s),s 为所有字符串的长度之和

class Solution {
    public String longestCommonPrefix(String[] strs) {
        if(strs.length==0)//字符串为空,返回
            return "";
        String ans = strs[0];//令第一个字符串为结果
        for (int i=1;i<strs.length;i++){
            int j=0;
            for(;j<ans.length() && j<strs[i].length();j++){
                if(ans.charAt(j)!=strs[i].charAt(j))
                break;
            }
            ans=ans.substring(0,j);
            if(ans.equals(""))
                return ans;
        }
         return ans;
    }
}

八、反转单词顺序(151+offer)

剑指offer
方法一:

class Solution {
    public String reverseWords(String s) {
        String[] strs = s.trim().split(" "); // 删除首尾空格,分割字符串
        StringBuilder res = new StringBuilder();
        for(int i = strs.length - 1; i >= 0; i--) { // 倒序遍历单词列表
            if(strs[i].equals("")) continue; // 遇到空单词则跳过
            res.append(strs[i] + " "); // 将单词拼接至 StringBuilder
        }
        return res.toString().trim(); // 转化为字符串,删除尾部空格,并返回
    }
}

方法二:双指针

class Solution {
    public String reverseWords(String s) {
        s = s.trim(); // 删除首尾空格
        int j = s.length() - 1, i = j;
        StringBuilder res = new StringBuilder();
        while(i >= 0) {
            while(i >= 0 && s.charAt(i) != ' ') i--; // 搜索首个空格
            res.append(s.substring(i + 1, j + 1) + " "); // 添加单词
            while(i >= 0 && s.charAt(i) == ' ') i--; // 跳过单词间空格
            j = i; // j 指向下个单词的尾字符
        }
        return res.toString().trim(); // 转化为字符串并返回
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值