Leetcode - String - Easy(14,28,58,125,344,383,387)

  1. Longest Common Prefix
    以第一个元素为基准值,挨个与其它元素进行比较。while 循环里面就是为了使基准值成为比较元素的起始字符串,故它不满足就每次截掉最后一位。若是全部截完了那就是无公共前缀了。
class Solution {
    public String longestCommonPrefix(String[] strs) {
        if(strs.length==0){return "";}
        String s = strs[0];
        for(int i=1;i<strs.length;i++){
            while(strs[i].indexOf(s)!=0){
                s=s.substring(0,s.length()-1);
                if(s.isEmpty()){
                    return "";
                }
            }
        }
        return s;
    }
}
  1. Implement strStr()
    Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
    For the purpose of this problem, we will return 0 when needle is an empty string. This is consistent to C’s strstr() and Java’s indexOf().
Example 1:
Input: haystack = "hello", needle = "ll"
Output: 2
Example 2:
Input: haystack = "aaaaa", needle = "bba"
Output: -1
Example 3:
Input: haystack = "", needle = ""
Output: 0

方法一:最直接的方法 - 沿着字符换逐步移动滑动窗口,将窗口内的子串与 needle 字符串比较。
时间复杂度:O((N - L)L),其中 N 为 haystack 字符串的长度,L 为 needle 字符串的长度。内循环中比较字符串的复杂度为 L,总共需要比较 (N - L) 次。
空间复杂度:O(1)。

class Solution {
    public int strStr(String haystack, String needle) {
        int hl=haystack.length(), nl=needle.length();
        for(int i=0;i<=hl-nl;i++){
            if(haystack.substring(i,i+nl).equals(needle)){
                return i;
            }
        }
        return -1;
    }
}

方法二:双指针,理论上得到改进,实际运行速度和方法一差不多
移动 pn 指针,直到 pn 所指向位置的字符与 needle 字符串第一个字符相等。
通过 pn,pL,curr_len 计算匹配长度。
如果完全匹配(即 curr_len == L),返回匹配子串的起始坐标(即 pn - L)。
如果不完全匹配,回溯。使 pn = pn - curr_len + 1, pL = 0, curr_len = 0。

class Solution {
  public int strStr(String haystack, String needle) {
    int L = needle.length(), n = haystack.length();
    if (L == 0) return 0;

    int pn = 0;
    while (pn < n - L + 1) {
      // find the position of the first needle character
      // in the haystack string
      while (pn < n - L + 1 && haystack.charAt(pn) != needle.charAt(0)) pn++;

      // compute the max match string
      int currLen = 0, pL = 0;
      while (pL < L && pn < n && haystack.charAt(pn) == needle.charAt(pL)) {
        pn++;
        pL++;
        currLen++;
      }

      // if the whole needle string is found,
      // return its start position
      if (currLen == L) return pn - L;

      // otherwise, backtrack
      pn = pn - currLen + 1;
    }
    return -1;
  }
}

方法三是根据网友总结的动态规划KMP算法,但提交后跑出来复杂度略高,理论和实际似乎有一道鸿沟。

class Solution {
  public int strStr(String haystack, String needle) {
      int nl=needle.length();
      if(nl==0) return 0;
      int[][] dp = new int[nl][256];
      dp[0][needle.charAt(0)]=1;
      int X = 0;
      for(int j=1;j<nl;j++){
          for(int c=0;c<256;c++){
              if(needle.charAt(j)==c){
                  dp[j][c]=j+1;
              }else{
                  //System.out.println("j="+j+",X="+X);
                  dp[j][c]=dp[X][c];
              }
          }
           X=dp[X][needle.charAt(j)];
      }
      
      int hl= haystack.length();
      int k=0;
      for(int i=0;i<hl;i++){
          k=dp[k][haystack.charAt(i)];
          if(k==nl) return i-nl+1;
      }
      return -1;
  }
}

最后贴出正统KMP写法,跑完复杂度比前面一个版本好很多,但略差于方法一二。
目前理解还是有点迷糊,参考学习视频

class Solution {
    public int strStr(String haystack, String needle) {
        int hlength=haystack.length();
        int nlength=needle.length();
        
        if(nlength==0) return 0;
        if(nlength>hlength) return -1;
        if(nlength==hlength && needle.equals(haystack)) return 0;
        
        int[] next = KMP(needle);
        int start=0,i=0;
        while(start<=hlength-nlength){
            if(haystack.charAt(start+i)==needle.charAt(i)){
                i++;
                if(i==nlength) return start;
            }else{
                start=start+i-next[i];
                i = i>0? next[i] : 0;
            }
        }
        return -1;
    }
    
    private int[] KMP(String needle){
        int len=needle.length();
        int[] next = new int[len];
        next[0]=-1;
        if(len>1) next[1]=0;
        int i=2;
        int j=0;
        while(i<len){
            if(needle.charAt(i-1)==needle.charAt(j)){
                next[i]=j+1;
                j++;
                i++;
            }else if(j>0){
                j=next[j];
            }else{
                next[i]=0;
                i++;
            }
        }
        return next;
        
    }
}

The count-and-say sequence is a sequence of digit strings defined by the recursive formula:

Example 
Input: n = 4
Output: "1211"
Explanation:
countAndSay(1) = "1"
countAndSay(2) = say "1" = one 1 = "11"
countAndSay(3) = say "11" = two 1's = "21"
countAndSay(4) = say "21" = one 2 + one 1 = "12" + "11" = "1211"

1 被读作 “one 1” (“一个一”) , 即 11。
11 被读作 “two 1” (“两个一”), 即 21。
21 被读作 “one 2”, “one 1” (“一个二” , “一个一”) , 即 1211。
给定一个正整数 n(1 ≤ n ≤ 30),输出外观数列的第 n 项。
阅读困难题,主要理解这个数字是从前一个读出来的。所以做n-1个循环。每个循环内遍历上一个得出的String,记录重复个数进StringBuilder里。

class Solution {
    public String countAndSay(int n) {
        String s="1";
        for(int i=1;i<n;i++){
            StringBuilder sb=new StringBuilder();
            for(int j=0;j<s.length();j++){
                int k=j;
                while(k<s.length() && s.charAt(k)==s.charAt(j)) k++;
                sb.append(k-j);
                sb.append(s.charAt(j));
                j=k-1; //注意循环里j++,所以这里要-1
            }
            s=sb.toString();
        }
        return s;
    }
}
  1. Length of Last Word
    Given a string s consists of some words separated by spaces, return the length of the last word in the string. If the last word does not exist, return 0.

A word is a maximal substring consisting of non-space characters only.

Example 1:
Input: s = "Hello World"
Output: 5
Example 2:
Input: s = " "
Output: 0

要注意特殊例子"aa "的情况,可能一开始后面就有🈳️。所以返回条件为count>0 && s.charAt(i) == ’ '

class Solution {
    public int lengthOfLastWord(String s) {
        int count=0;
        for(int i=s.length()-1;i>=0;i--){
            if(count>0 && s.charAt(i) == ' '){
                return count;
            }else if(s.charAt(i)!= ' '){
                count++;
            }
        }
        return count;
    }
}

另外可以用s.trim() 的方法来去除前后空格简化。下面这个方法用空格分割出最后一个单词后返回单词长度。

class Solution {
    public int lengthOfLastWord(String s) {
        s=s.trim();
        if(s.isEmpty()) return 0;
        String[] splitstring=s.split(" ");
        String last = splitstring[splitstring.length-1];
        return last.length();
    }
}
  1. Valid Palindrome
    Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
    Note: For the purpose of this problem, we define empty string as valid palindrome.
Example 1:
Input: "A man, a plan, a canal: Panama"
Output: true
Example 2:
Input: "race a car"
Output: false

方法一是双指针,前后2⃣️指针往中间读取,忽略非字母数字的字符。

class Solution {
    public boolean isPalindrome(String s) {
        char[] c = s.toLowerCase().toCharArray();
        int i=0,j=c.length-1;
        while(i<j){
            if(!Character.isLetterOrDigit(c[i])){
                i++;
            }else if(!Character.isLetterOrDigit(c[j])){
                j--;
            }else{
                if(c[i] == c[j]){
                    i++;
                    j--;
                 }else{
                    return false;
                } 
            }         
        }
        return true;
    }
}

方法二是利用StringBuilder.reverse()的作弊方法。

class Solution {
    public boolean isPalindrome(String s) {
        StringBuilder sb = new StringBuilder();
        for(int i=0;i<s.length();i++){
            char c = s.charAt(i);
            if(Character.isLetterOrDigit(c)){
                sb.append(Character.toLowerCase(c));
            }
        }
        StringBuilder reverse = new StringBuilder(sb).reverse();
        return sb.toString().equals(reverse.toString());      
    }
}

方法三避免了用reverse作弊,用stack保存前半截string,然后一个个弹出来和后半截比较。注意pop出来的类型。

class Solution {
    public boolean isPalindrome(String s) {
        StringBuilder sb = new StringBuilder();
        for(int i=0;i<s.length();i++){
            char c = s.charAt(i);
            if(Character.isLetterOrDigit(c)){
                sb.append(Character.toLowerCase(c));
            }
        }
        
        Stack stack = new Stack();
        for(int i=0;i<sb.length()/2;i++){
            stack.push(sb.charAt(i));
        }
        
        int start = sb.length()%2==0? sb.length()/2 : sb.length()/2+1;
        while(!stack.isEmpty()){
            if((char)stack.pop()!=sb.charAt(start)){
                return false;
            }else{
                start++;
            }
        }
        return true;
    }
}
  1. Reverse String
    Write a function that reverses a string. The input string is given as an array of characters char[].
    Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
Example 1:
Input: ["h","e","l","l","o"]
Output: ["o","l","l","e","h"]
class Solution {
    public void reverseString(char[] s) {
        int i=0,j=s.length-1;
        while(i<j){
            char tmp = s[i];
            s[i++]=s[j];
            s[j--]=tmp;
        }
    }
}
  1. Reverse Vowels of a String
    Write a function that takes a string as input and reverse only the vowels of a string.
    Example 1:
    Input: “hello”
    Output: “holle”
    利用char[] <–> string之间的转化和双指针完成。
class Solution {
    public String reverseVowels(String s) {
        int i=0,j=s.length()-1;
        char[] c =s.toCharArray();
        while(i<j){
            if(isVowel(c[i]) && isVowel(c[j])){
                char tmp = c[i];
                c[i++]=c[j];
                c[j--]=tmp;
            }else if(!isVowel(c[i])){
                i++;
            }else{
                j--;
            }
        }
        return new String(c);             
    }
    private boolean isVowel(char c){
        return c=='a' || c=='e' || c=='i' || c=='o' || c=='u' ||c=='A' || c=='E' || c=='I' || c=='O' || c=='U';
    }
}
  1. Ransom Note
    Given an arbitrary ransom note string and another string containing letters from all the magazines, write a function that will return true if the ransom note can be constructed from the magazines ; otherwise, it will return false.
    Each letter in the magazine string can only be used once in your ransom note.
Example 1:
Input: ransomNote = "a", magazine = "b"
Output: false
Example 2:
Input: ransomNote = "aa", magazine = "ab"
Output: false
Example 3:
Input: ransomNote = "aa", magazine = "aab"
Output: true

直白的思路就是用HashMap计数,看别人用python写更简单,一个循环比较count(i)即可

class Solution {
    public boolean canConstruct(String ransomNote, String magazine) {
        Map<Character,Integer> map = new HashMap<>();
        for(int i=0;i<magazine.length();i++){
            char c = magazine.charAt(i);
            map.put(c,map.getOrDefault(c,0)+1);
        }
        for(int j=0;j<ransomNote.length();j++){
            char c = ransomNote.charAt(j);
            if(map.containsKey(c) && map.get(c)>=1){
                map.put(c,map.get(c)-1);
            }else{
                return false;
            }
        }
        return true;
    }
}
class Solution(object):
    def canConstruct(self, ransomNote, magazine):
        """
        :type ransomNote: str
        :type magazine: str
        :rtype: bool
        """
        for i in set(ransomNote):
            if ransomNote.count(i) > magazine.count(i):
                return False
        return True
  1. First Unique Character in a String
    Given a string, find the first non-repeating character in it and return its index. If it doesn’t exist, return -1.
Examples:
s = "leetcode"
return 0.
s = "loveleetcode"
return 2.

类似上一题也可以用HashMap记录string中字母出现次数。不过这次用Array记录,空间复杂度更小,a对应arr[0], 以此类推。

class Solution {
    public int firstUniqChar(String s) {
        int[] arr = new int[26];
        for(int i=0;i<s.length();i++){
            char c=s.charAt(i);
            arr[c-'a']+=1;
        }
        for(int i=0;i<s.length();i++){
            char c=s.charAt(i);
            if(arr[c-'a']==1){
                return i;
            }
        }
        return -1;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值