一文搞定String

数据结构与算法/leetcode/lintcode题解

String

String 相关的题常出现在面试题中,实际开发也经常用到,这里总结下 C++, Java, Python 中字符串常用的方法。

Python

s1 = str()
# in python `''` or `""` is the same
s2 = "shaunwei" # 'shaunwei'
s2len = len(s2)
# last 3 chars
s2[-3:] # wei
s2[5:8] # wei
s3 = s2[:5] # shaun
s3 += 'wei' # return 'shaunwei'
# list in python is same as ArrayList in java
s2list = list(s3)
# string at index 4
s2[4] # 'n'
# find index at first
s2.index('w')  # return 5, if not found, throw ValueError
s2.find('w') # return 5, if not found, return -1

在Python里面,没有StringBuffer 或者 StringBuilder。 但是在Python 里面处理String本身就比较 cheap。

Java

String s1 = new String();
String s2 = "billryan";
int s2Len = s2.length();
s2.substring(4, 8); // return "ryan"
StringBuilder s3 = new StringBuilder(s2.substring(4, 8));
s3.append("bill");
String s2New = s3.toString(); // return "ryanbill"
// convert String to char array
char[] s2Char = s2.toCharArray();
// char at index 4
char ch = s2.charAt(4); // return 'r'
// find index at first
int index = s2.indexOf('r'); // return 4. if not found, return -1

StringBuffer 与 StringBuilder, 前者保证线程安全,后者不是,但单线程下效率高一些,一般使用 StringBuilder.

Coding

对于一个给定的 source 字符串和一个 target 字符串,你应该在 source 字符串中找出 target 字符串出现的第一个位置(从0开始)。如果不存在,则返回 -1

public class Solution {
    public int strStr(String source, String target) {
        if(source == null || target == null) {
            return -1;
        }
        if(source.length() == 0 && target.length() == 0) {
            return 0;
        }
        if(target.length() == 0) {
            return 0;
        }
        for(int i = 0; i < source.length(); i++) {
            int tmp = i;
            int j = 0;
            for(; j < target.length() && tmp < source.length() && target.charAt(j) == source.charAt(tmp);) {
                j++;
                tmp++;
            }
            if(j == target.length()) {
                return i;
            }
        }
        return -1;
    }
}

写出一个函数 anagram(s, t) 判断两个字符串是否可以通过改变字母的顺序变成一样的字符串。

import java.util.HashMap;
import java.util.Map;
//使用Map
public class Solution {
    /**
     * @param s: The first string
     * @param t: The second string
     * @return: true or false
     */
    public boolean anagram(String s, String t) {
        if(s.length() != t.length()) {
            return false;
        }
        Map<Character, Integer> map = new HashMap<>();
        for(int i = 0; i < s.length(); i++) {
            if(!map.containsKey(s.charAt(i))) {
                map.put(s.charAt(i), 1);
            } else {
                int temp = map.get(s.charAt(i)) + 1;
                map.put(s.charAt(i), temp);         
            }  
        }
        for(int j = 0; j < t.length(); j++) {
            if(!map.containsKey(t.charAt(j))) {
                return false;
            }
            int temp = map.get(t.charAt(j)) - 1;
            map.put(t.charAt(j), temp);
        }
        for(Character key : map.keySet()) {
            if(map.get(key) != 0) {
                return false;
            }
        }
        return true;
    }
}
public class Solution {
    /**
     * @param s: The first string
     * @param t: The second string
     * @return: true or false
     */
    //使用数组存储,更方便
    public boolean anagram(String s, String t) {
        if(s.length() != t.length()) return false;
        if(s == null || t == null) return false;
        final int CHAR_NUM = 256;
        int[] arr  = new int[CHAR_NUM];
        for(int i = 0; i < s.length(); i++) {
            arr[s.charAt(i)]++;
            arr[t.charAt(i)]--;
        }
        for(int j = 0; j < arr.length; j++) {
            if(arr[j] != 0) {
                return false;
            }
        }
        return true;
    }
}

猜你喜欢

转载自blog.csdn.net/u013015065/article/details/80188723