leedcode 初级题 (Strings 系列)

1、字符串倒叙排列。

Write a function that takes a string as input and returns the string reversed.

Example 1:

Input: "hello"
Output: "olleh"
Example 2:

Input: "A man, a plan, a canal: Panama"
Output: "amanaP :lanac a ,nalp a ,nam A"

//方法一
class Solution {
    public String reverseString(String s) { 
        char temp;
        int n = s.length();
        char[] myChar=s.toCharArray();//不用指定长度?字符串指定长度?
        for(int i=0;i<n/2;i++)//小心错误,不能为 i<n,则交换了两次又交换成了hello
        {
            temp=myChar[i];
            myChar[i]=myChar[n-i-1];
            myChar[n-i-1]=temp; 
        }
       return new String(myChar);               
    }
}


2、整数倒叙问题。

Given a 32-bit signed integer, reverse digits of an integer.

Example 1:

Input: 123
Output: 321
Example 2:

Input: -123
Output: -321
Example 3:

Input: 120
Output: 21
Note:
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231,  231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

//方法 
class Solution {
    public int reverse(int x) {
        int result = 0;
        while(x!=0)
        {
            int tail = x%10;
            int newResult = result*10+tail;
            if((newResult-tail)/10!=result)//tail 可以省略 因为newResult/10已经去掉了末位
            {
                return 0;
            }
           result = newResult;
            x=x/10;
        }
    return result;
    }
    
}
as many others, I didn't get the line if ((newResult - tail) / 10 != result).

We're interested on what happens when an integer overflows. Well, it is rolled over. Practically speaking, if you would try

    public static void main(String[] args) {
        int rollMeOver= Integer.MAX_VALUE + 1;
        System.out.println(rollMeOver);
    }
You will get as an output -2147483648 which represents the lowest value for an integer (Integer.MIN_VALUE).

Thus, in our problem, if newResult is going to overflow we are sure that newResult / 10 != result (this is the reason that @Inception_wzd said that we don't need to subtract the tail first because by / 10 we are already losing the last digit).

By the way, the same thing happens for the underflow.

    public static void main(String[] args) {
        int rollMeOver= Integer.MIN_VALUE - 1;
        System.out.println(rollMeOver);
    }
This is going to output the Integer.MAX_VALUE which is 2147483647 .


3、寻找字符串中第一个不重复的字符。

Given a string, find the first non-repeating character in it and return it's index. If it doesn't exist, return -1.

Examples:

s = "leetcode"
return 0.

s = "loveleetcode",
return 2.
Note: You may assume the string contain only lowercase letters.

//常规解法 o(n^2)
class Solution {
    public int firstUniqChar(String s) {
        char [] myChar = s.toCharArray();
        int n = s.length();
        int j=0;
        while(j<n)
        {
             for(int i=0;i<n;i++)
            {
                if ((myChar[j]!=myChar[i])&&(i!=j)) 
                return j;

            }
            j++;
        }
       
    return -1;
    }
}

//解法二:

//Get the frequency of each character.
//Get the first character that has a frequency of one.
//Actually the code below passes all the cases. However, according to @xietao0221, we //could change the size of the frequency array to 256 to store other kinds of characters. 

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


4、寻找给定字符串的第一个非重复字符,可以假定只有小写字母。不存在的话返回-1。

Examples:

s = "leetcode"
return 0.

s = "loveleetcode",
return 2.

//方法1 最笨的
class Solution {
    public int firstUniqChar(String s) {
        char [] myChar = s.toCharArray();
        int n = s.length();
        int j=0;
        while(j<n)
        {
             for(int i=0;i<n;i++)
            {
                if ((myChar[j]!=myChar[i])&&(i!=j)) 
                return j;
            }
            j++;
        }
       
    return -1;
    }
}

//方法2 利用Set 和Map  开拓思路
class Solution {
    public int firstUniqChar(String s) {
        Map<Character, Integer> map = new LinkedHashMap<>();
        Set<Character> set = new HashSet<>();
        for (int i = 0; i < s.length(); i++) {
            if (set.contains(s.charAt(i))) {
                if (map.get(s.charAt(i)) != null) {
                    map.remove(s.charAt(i));
                }
            } else {
                map.put(s.charAt(i), i);
                set.add(s.charAt(i));
            }
        }
        return map.size() == 0 ? -1 : map.entrySet().iterator().next().getValue();
    }
}

//方法三 统计字符出现频率 后取出第一个频率为1的
public class Solution {
    public int firstUniqChar(String s) {
        int freq [] = new int[26];
        for(int i = 0; i < s.length(); i ++)
            freq [s.charAt(i) - 'a'] ++;
        for(int i = 0; i < s.length(); i ++)
            if(freq [s.charAt(i) - 'a'] == 1)
                return i;
        return -1;
    }
}


5、给定两个字符串,验证其中字符是否相等。

Example 1:

Input: s = "anagram", t = "nagaram"
Output: true
Example 2:

Input: s = "rat", t = "car"
Output: false
Note:
You may assume the string contains only lowercase alphabets.

Follow up:
What if the inputs contain unicode characters? How would you adapt your solution to such case?

class Solution {
    public boolean isAnagram(String s, String t) {
        int[] freq = new int[26];// int[128]  if unicode character.
        for(int i=0;i<s.length();i++) freq[s.charAt(i)-'a']++;
        for(int i=0;i<t.length();i++) freq[t.charAt(i)-'a']--;
        for(int i:freq) if(i!=0) return false;
        return true;
    }
}


6、检查是否是回文字符串,忽略特殊字符,只针对字母和数字,字母忽略大小写。

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

//方法一
class Solution {
   
    public boolean isPalindrome(String s) {
        if(s==null || s.length()==0)
            return true;
        int start=0, end = s.length()-1;
        while(start<=end){
           while(start<=end && !Character.isLetterOrDigit(s.charAt(start)))
               start++;
           while(start<=end && !Character.isLetterOrDigit(s.charAt(end)))
               end--;
            if(start<=end && Character.toUpperCase(s.charAt(start)) != Character.toUpperCase(s.charAt(end)))
                return false;
           start++; end--;
        }
        return true;
    }

}

//方法二

class Solution {
   
    public boolean isPalindrome(String s) {
        int i = 0;
        int j = s.length() - 1;
        char[] c = s.toCharArray();
        while (i < j) {
            while (i < s.length() && !valid(c[i])) i++;
            while (j >= 0 && !valid(c[j])) j--;
            if (i < j && Character.toLowerCase(c[i]) != Character.toLowerCase(c[j])) {
                return false;
            }
            i++;
            j--;
        }
        return true;
    }
    
    public boolean valid(char c) {
        return (c >= 'a' && c <= 'z') ||
               (c >= 'A' && c <= 'Z') ||
               (c >= '0' && c <= '9');
    }
}


7、字符串转化为有符号整数,要考虑溢出情况。

Implement atoi which converts a string to an integer.

The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.

The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.

If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.

If no valid conversion could be performed, a zero value is returned.

Note:

Only the space character ' ' is considered as whitespace character.
Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231,  231 − 1]. If the numerical value is out of the range of representable values, INT_MAX (231 − 1) or INT_MIN (−231) is returned.
Example 1:

Input: "42"
Output: 42
Example 2:

Input: "   -42"
Output: -42
Explanation: The first non-whitespace character is '-', which is the minus sign.
             Then take as many numerical digits as possible, which gets 42.
Example 3:

Input: "4193 with words"
Output: 4193
Explanation: Conversion stops at digit '3' as the next character is not a numerical digit.
Example 4:

Input: "words and 987"
Output: 0
Explanation: The first non-whitespace character is 'w', which is not a numerical 
             digit or a +/- sign. Therefore no valid conversion could be performed.
Example 5:

Input: "-91283472332"
Output: -2147483648
Explanation: The number "-91283472332" is out of the range of a 32-bit signed integer.
             Thefore INT_MIN (−231) is returned.

//注意The Integer.MAX_VALUE 为2147483647 而Integer.MIN_VALUE 为 -2147483648.
// 判断是否大于2147483647
class Solution {
   public int myAtoi(String str) {
        int sign = 1, base = 0, i = 0, INT_MAX = Integer.MAX_VALUE, INT_MIN = Integer.MIN_VALUE;
        while (i < str.length() && str.charAt(i) == ' ') i++;
        
        if (i >= str.length()) return 0;
        
        if (str.charAt(i) == '+' || str.charAt(i) == '-') {
            if (str.charAt(i) == '-') sign = -1;
            i++;
        }
        
        while (i < str.length() && str.charAt(i) >= '0' && str.charAt(i) <= '9') {
            if (base > INT_MAX / 10 || (base == INT_MAX / 10 && str.charAt(i) - '0' > 7)) {
                if (sign == -1) return INT_MIN;
                else            return INT_MAX;    
            }
            base = 10 * base + (str.charAt(i++) - '0');
        }
        
        return base * sign;
        
    }
}

8、检查子字符串。

Implement strStr().

Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

Example 1:

Input: haystack = "hello", needle = "ll"
Output: 2
Example 2:

Input: haystack = "aaaaa", needle = "bba"
Output: -1
Clarification:

What should we return when needle is an empty string? This is a great question to ask during an interview.

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().

//常用解法
class Solution {
    public int strStr(String haystack, String needle) {
        int j=0,i=0;
            if (haystack.length()< needle.length()) {
            return -1;
        } else if (needle.length() == 0) {
            return 0;
        }
        while(i<haystack.length()&&j<needle.length())
        {   
            if(haystack.charAt(i)!=needle.charAt(0))
            {
                i++;
            }
                
            else if(haystack.charAt(i)==needle.charAt(j))
            {
                //final int k = i;
                 j++;
                 i++;
            } 
            if (j==needle.length()) return i-j;
             
            
       }
        
        return -1;
    }
}

//解法2,思路不错,但是可能公司不会让你用内置方法
public class Solution {
    public int strStr(String haystack, String needle) {
        int l1 = haystack.length(), l2 = needle.length();
        if (l1 < l2) {
            return -1;
        } else if (l2 == 0) {
            return 0;
        }
        int threshold = l1 - l2;
        for (int i = 0; i <= threshold; ++i) {
            if (haystack.substring(i,i+l2).equals(needle)) {
                return i;
            }
        }
        return -1;
    }
}


9、对给定特征的序列进行输出。

The count-and-say sequence is the sequence of integers with the first five terms as following:

1.     1
2.     11
3.     21
4.     1211
5.     111221
1 is read off as "one 1" or 11.
11 is read off as "two 1s" or 21.
21 is read off as "one 2, then one 1" or 1211.

Given an integer n where 1 ≤ n ≤ 30, generate the nth term of the count-and-say sequence.

Note: Each term of the sequence of integers will be represented as a string.

 

Example 1:

Input: 1
Output: "1"
Example 2:

Input: 4
Output: "1211"


//说明:只针对题目中给定的序列,没有其他序列
//扩展后更容易理解
 1.     1
 2.     11
 3.     21
 4.     1211
 5.     111221 
 6.     312211
 7.     13112221
 8.     1113213211
 9.     31131211131221
 10.   13211311123113112211

//解法看似简单,对于不熟悉的人可能容易卡住
class Solution {
    public String countAndSay(int n) {
        String s = "1";
        //StringBuilder s = new StringBuilder("1");        
        for(int i=1;i<n;i++)
        {
            s = stringBack(s);         
        }
        return s;
    }
    
    public String stringBack(String s)
    {
        StringBuilder sb = new StringBuilder();
        char c = s.charAt(0);
        int count = 1;        
        for(int j=0;j<s.length();j++)
        {
            if(s.charAt(j)==c)
                count++;
            else
            {
                sb.append(count);
                sb.append(c);
                c = s.charAt(j);
                count=1;
            }
        }
        return sb.toString();
    }
    
}


10、在给定字符串数组中,求各字符串的共同前缀。

Write a function to find the longest common prefix string amongst an array of strings.

If there is no common prefix, return an empty string "".

Example 1:

Input: ["flower","flow","flight"]
Output: "fl"
Example 2:

Input: ["dog","racecar","car"]
Output: ""
Explanation: There is no common prefix among the input strings.
Note:

All given inputs are in lowercase letters a-z.

//注意substring的用法,实际取值为前闭后开,                                             
//如substring(0,2)实际为[0,2),只取到pre[0],pre[1],取不到pre[2]
//数组的初始化必须要用new String[]{赋值},直接{赋值}不对
lass Solution {
  public String longestCommonPrefix(String[] strs) {
    if(strs == null || strs.length == 0)    return "";
    String pre = strs[0];
    int i = 1;
    while(i < strs.length){
        while(strs[i].indexOf(pre) != 0)
            pre = pre.substring(0,pre.length()-1);//pre字符从后递减
        i++;
    }
    return pre;
}
}

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值