LeetCode 之 string字符串一

图解LeetCode97:Interleaving String 文章目录理解题意解决方法一:最简单解法解决方法二:动态规划代码实现总结 Leetcode算法系列将详细讲解一些经典的面试算法题。 今天的题目是个人非常喜欢的一个,题目的名字叫做“Interleaving String”,这个题目是什么意思呢?   理解题意 Interleaving 从字面上讲是交错交叉的意思,给定两个字符串s1:"a"和s2:“b”,那么对于s3:"ab"我们说s3是s... 阅读详情

1. Length of last word

Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string.

If the last word does not exist, return 0.

Note: A word is defined as a character sequence consists of non-space characters only.

For example, 
Given s = "Hello World",
return 5.

这是一道实现题,从后往前扫描,如何判断最后一个word,有以下几种情况

1.“word   ”

2. "       "

3. "word"

4."  word  "

int lengthOfLastWord(const char *s) {
    int length = strlen(s);
    int count = 0;
    for(int i= length-1; i>=0;i--){
        if(s[i] == ' '){
            if(count == 0) continue;
            else return count;
        }
        count++;
    }
    return count;
}

Java解法:

利用split()函数,通过空格“ ”将原字符串分组

public int lengthOfLastWord(String s) {
        String [] splitStrings = s.split(" ");
        	for(int i=splitStrings.length-1;i>=0;i--){
        		if(splitStrings[i].length()>0)
        			return splitStrings[i].length();
        	}
        	return 0;
    }



2. Longest Common Prefix

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

字符串搜索,实现题。

定义一个compare string存放最后结果,遍历数组,每次找到相应的prefix存到compare中

string longestCommonPrefix(vector<string> &strs) {
    if(strs.size() == 0) return NULL;
    string compare = strs[0];
    for(int i=1; i<strs.size();i++){
        string prefix;
        int k=0;
        while(k<compare.size() && k<strs[i].size()){
            if(compare[k] != strs[i][k]) break;

            prefix.append(1,compare[k]);
            k++;
        }
        compare.clear();
        compare.append(prefix.c_str());
    }
    return compare;
}

解法二

scan from the first character, if it is same to all other strings, then scan the second one until meet different or null

java实现

public String longestCommonPrefix(String[] strs) {
        if(strs.length == 0) return "";
        boolean flag = true;
		for(int i=0;i<strs[0].length();i++){
			for(int j=0;j<strs.length;j++){
				if(i>=strs[j].length() || strs[0].charAt(i)!=strs[j].charAt(i)){
					flag = false;
					break;
				}
			}
			if(!flag) return strs[0].substring(0,i);
		}
		return strs[0];
    }



3.Count and Say

The count-and-say sequence is the sequence of integers beginning as follows:
1, 11, 21, 1211, 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, generate the nth sequence.

Note: The sequence of integers will be represented as a string.

字符串操作,n次循环构造第n个字符串,构造过程通过数前面的字符。注意这里用i<=result.size() 省去判断到达字符串末尾

 
string countAndSay(int n) {
    string result = "1";
    int level = 1;
    while(level < n){
        stringstream seq;
        char last = result[0];
        int count =0;
        for(int i=0; i<=result.size();i++){
            if(result[i] == last){
                count++;
                continue;
            }
            else{
                seq<<count<<last;
                count = 1;
                last = result[i];
            }
        }
        result = seq.str();
        level++;
    }
    return result;
}

Java

public String countAndSay(int n) {
        String result = "1";
        if(n==1) return result;
        int level = 1;
        while(level<n){
        	char last = result.charAt(0);
        	int count =0;
        	StringBuffer seq = new StringBuffer();
        	for(int i=0;i<result.length();i++){
        		if(last == result.charAt(i)){
        			count++;
        			continue;
        		}else {
					seq.append(count);
					seq.append(last);
					last = result.charAt(i);
					count=1;
				}
        	}
        	seq.append(count);
			seq.append(last);
        	result = seq.toString();
        	level++;
        }
        return result;
    }


4. 

Implement strStr().

Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.

时间复杂度线性的解法明显是KMP算法

1. 普通的解法。

2. KMP 算法---算法导论32章

char *strStr(char *haystack, char *needle) {
    if(haystack == NULL || needle == NULL) return NULL;
    int hlength = strlen(haystack);
    int nlength = strlen(needle);
    if(hlength<nlength) return NULL;
    for(int i=0; i<hlength-nlength+1;i++){
        char *p = &haystack[i];
        int j=0;
        for(;j<nlength;j++){
            if(*p == needle[j])
                p++;
            else
                break;
        }
        if(j == nlength)
            return --p;
    }
    return NULL;
}

方法2

public String strStr(String haystack, String needle) {
		if(haystack.length()<=0 && needle.length()>0) return null;
        for(int i=0;i<=haystack.length()-needle.length();i++){
        	boolean flag = true;
        	for(int j=0;j<needle.length();j++){
        		if(haystack.charAt(i+j)!=needle.charAt(j)){
        			flag = false;
        			break;
        		}
        	}
        	if(flag){
    			return haystack.substring(i);
    		}
        }
        return null;
    }


方法3

参考

http://blog.youkuaiyun.com/lin_bei/article/details/1252686

算法导论32章


5. Valid Palindrome

Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.

For example,
"A man, a plan, a canal: Panama" is a palindrome.
"race a car" is not a palindrome.

Note:
Have you consider that the string might be empty? This is a good question to ask during an interview.

For the purpose of this problem, we define empty string as valid palindrome.

Analysis:

Use Two pointers, scan from end to start.

Java

public boolean isPalindrome(String s) {
        s = s.trim();
		if(s.length()<=0) return true;
		int start = 0;
		int end = s.length()-1;
		while(start<end){
			while(start<end && !(Character.isLetter(s.charAt(start))||Character.isDigit(s.charAt(start)))) start++;
			while(start<end &&  !(Character.isLetter(s.charAt(end))||Character.isDigit(s.charAt(end)))) end--;
			if(s.charAt(start)==s.charAt(end) || s.charAt(start)-'a'==s.charAt(end)-'A'||s.charAt(start)-'A' == s.charAt(end)-'a' ){
			start++;
			end--;
			}else {
				break;
			}
		}
		if(start>=end)
			return true;
		else {
			return false;
		}
    }

Another one:

public boolean isPalindrome(String s) {
        if(s.isEmpty()) return true;
        int len = s.length();
        int start = 0;
        int end = len-1;
        while(start<=end){
        	if(!isAlp(s.charAt(start))){
        		start++;
        		continue;
        	}
        	if(!isAlp(s.charAt(end))){
        		end--;
        		continue;
        	}
        	if(s.charAt(start)==s.charAt(end) || Math.abs(s.charAt(start)-s.charAt(end))==32){
        		start++;
				end--;
        	}else
        		return false;
        	
        }
        return true;
    }
	public boolean isAlp(char c){
		if((c<='z'&&c>='a')||(c<='Z'&&c>='A')|| (c>='0'&&c<='9'))
			return true;
		else
			return false;
	}


c++

bool isPalindrome(string s) {
      if(s.empty()) return true;
    int len = s.length();
    int r = len-1;
    int l = 0;
    while(l<=r){
        if((s[l] >= 'a' && s[l]<='z') || (s[l]>='A' && s[l]<='Z')||(s[l])>='0'&& s[l]<='9'){
            if((s[r] >= 'a' && s[r]<='z') || (s[r]>='A' && s[r]<='Z')||(s[r]>='0' && s[r]<='9')){
                if(s[l] == s[r] || s[l]-'a'==s[r]-'A' || s[l]-'A' == s[r]-'a'){
                    l++;
                    r--;
                }
                else
                    return false;
            }else{
                r--;
                continue;
            }
        }

        else{
            l++;
            continue;
        }
    }
    return true;
    }




6. Reverse words in a string

Given an input string, reverse the string word by word.

For example,
Given s = "the sky is blue",
return "blue is sky the".

click to show clarification.

Clarification:

  • What constitutes a word?
    A sequence of non-space characters constitutes a word.
  • Could the input string contain leading or trailing spaces?
    Yes. However, your reversed string should not contain leading or trailing spaces.
  • How about multiple spaces between two words?
    Reduce them to a single space in the reversed string.

java实现
public String reverseWords(String s) {
        String newString = s.trim();
		if(newString.length()<=0) return s.trim();
		String []splitsStrings = newString.split(" ");
		int len = splitsStrings.length;
		StringBuilder sBuilder = new StringBuilder("");
		for(int i=len-1;i>=0;i--){
			if(splitsStrings[i].length()>0){
				sBuilder.append(splitsStrings[i]);
				sBuilder.append(" ");
			}
		}
		String resultString = sBuilder.toString();
		return resultString.trim();
    }
  • public String trim()
    Returns a copy of the string, with leading and trailing whitespace omitted.

    If this String object represents an empty character sequence, or the first and last characters of character sequence represented by thisString object both have codes greater than '\u0020' (the space character), then a reference to thisString object is returned.

    Otherwise, if there is no character with a code greater than '\u0020' in the string, then a newString object representing an empty string is created and returned.

    Otherwise, let k be the index of the first character in the string whose code is greater than'\u0020', and let m be the index of the last character in the string whose code is greater than'\u0020'. A new String object is created, representing the substring of this string that begins with the character at indexk and ends with the character at index m-that is, the result ofthis.substring(k, m+1).

    This method may be used to trim whitespace (as defined above) from the beginning and end of a string.

    Returns:
    A copy of this string with leading and trailing white space removed, or this string if it has no leading or trailing white space.
  • StringBuilder
    public StringBuilder(String str)
    Constructs a string builder initialized to the contents of the specified string. The initial capacity of the string builder is 16 plus the length of the string argument.
    Parameters:
    str - the initial contents of the buffer.
    Throws:
    NullPointerException - if str is  null

C++

Analysis:

The clarification is  very important, during the interview, one should think of these points without hint, and then implement the algorithm.

By checking the clarifications, the programming is straightforward, here provides a simple version which uses buffer strings:
(1) Loop from start to the end of the string:
          (a) if current char is space and word string is empty, continue.
          (b) if current char is space but word string is NOT empty, which means we meet the end of word, then output the word, reset the word, continue.
          (c) if current char is non-space char, add this char to the word string, continue
(2) Handle the last word:
      (a) if the last word is empty, which means the input is empty, or the input has only spaces, or the last char/chars are spaces.  Then just remove the last space in the output string and return.
      (b) if the last word is not empty, add the last word to the front of the output string, then remove the last space in the output string and return.

void reverseWords(string &s) {
    string word;//tmp string to store each word
    string res;// result string
    int i = 0;
    for(int i=0;i<s.size();i++){
        if(s[i]==' ' && word.empty()) continue;//multiple spaces
        if(s[i]==' ' && !word.empty()){// word ends
            res = word+" "+res;// add word to result string
            word = "";// reset the word
            continue;
        }
        if(s[i]!=' '){//non space characters
            word.push_back(s[i]);
            continue;
        }
    }
    if(!word.empty())//last word
        s = word+" "+res;
    else
        s = res;
    s = s.substr(0,s.size()-1);
}




7. 

Substring with Concatenation of All Words

You are given a string, S, and a list of words, L, that are all of the same length. Find all starting indices of substring(s) in S that is a concatenation of each word in L exactly once and without any intervening characters.

For example, given:
S: "barfoothefoobarman"
L: ["foo", "bar"]

You should return the indices: [0,9].
(order does not matter).

Analysis:

Try to think this problem straightforward:
Say in L there are m strings with length n. 
What string is required to match in S?     A length of m*n string start with each position in S.
What is a match?  In the m*n long string, every string in L appear only once.

So the algorithm is:
Scan every m*n long string start from each position in S, see if all the strings in L have been appeared only once using Map data structure. If so, store the starting position.

Yes, do not consider any DP or DFS solutions, just using the hash map and loop.

注意考虑L中可能含有重复字符串,需要用两个map

c++实现

vector<int> findSubstring(string S, vector<string> &L) {
        map<string, int> expectCount;
    map<string, int> realCount;
    vector<int> result;
    int row = L.size();
    if(row == 0) return result;
    int len = (int)L[0].size();
    for(int i=0; i< L.size(); i++){
        expectCount[L.at(i)]++;
    }
    for(int i=0; i<=(int)S.size()- row*len;i++){
        realCount.clear();
        int j=0;
        for(; j<row; j++){
            string str = S.substr(i+j*len,len);
            if(expectCount.find(str) != expectCount.end()){
                realCount[str]++;
            }else{
                break;
            }
            if(realCount[str]>expectCount[str])
                break;
        }
        if(j == row)
            result.push_back(i);
    }
    return result;
    }


Java实现

public ArrayList<Integer> findSubstring(String S, String[] L) {
        ArrayList<Integer> result = new ArrayList<Integer>();
        int num = L.length;
        int eachLen = L[0].length();
        if(num == 0 || eachLen ==0) return result;
        HashMap<String, Integer> hMap2 = new HashMap<String,Integer>();
    	for(int j=0;j<num;j++){
        	int val = 1;
			if(hMap2.containsKey(L[j])){
        		val = hMap2.get(L[j]);
        		val++;
			}
    		hMap2.put(L[j], val);
    	}
        for(int i=0;i<=S.length()-num*eachLen;i++){
        	HashMap<String, Integer> hMap = new HashMap<String,Integer>();
        	for(int j=0;j<num;j++){
        		hMap.put(L[j], 0);
        	}
        	int k =0 ;
        	while(k<num){
        		String str = S.substring(i+k*eachLen, i+eachLen*(k+1));
        		if(hMap.containsKey(str)){
        			int val = hMap.get(str);
        			hMap.put(str, ++val);
        			if(hMap.get(str)>hMap2.get(str)) break;
        			
        		}else{
        			break;
        		}
        		k++;
        	}
        	if(k == num) result.add(i);
        }
        
        return result;
    }

8.Minimum Window Substring

Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n).

For example,
S = "ADOBECODEBANC"
T = "ABC"

Minimum window is "BANC".

Note:
If there is no such window in S that covers all characters in T, return the emtpy string "".

If there are multiple such windows, you are guaranteed that there will always be only one unique minimum window in S.

Analysis:

Use two map to store the expected char occured numbers(from T), realtime char occured numbers(From S)

Since we should implement this with O(n), we scan string S from the start to the end, use appeared varablile to recored how many chars have occued compared with T

If the (char is in T && its occued numbers < T), store it and its occued numbers in expectedMap, appeared++

If(appeared == T.lenth() )// substring could cover all chars in T

while(starting char is not in T || starting char numbers > expected number in T)

starting index++

if(win_len> current window length)

set new window

return ....


C++实现如下

string minWindow(string S, string T) {
        if(S.size() == 0) return "";
    if(T.size() > S.size()) return "";
    int appearCount[256];
    int expectCount[256];
    memset(appearCount,0,256*sizeof(appearCount[0]));
    memset(expectCount,0,256*sizeof(appearCount[0]));

    for(int i=0; i<T.size();i++){
        expectCount[T[i]]++;
    }
    int minV = INT_MAX, min_start=0;
    int wid_start =0;
    int appeared = 0;

    for(int wid_end = 0; wid_end<S.size(); wid_end++){
        if(expectCount[S[wid_end]] >0)
        {
            appearCount[S[wid_end]]++;
            if(appearCount[S[wid_end]] <= expectCount[S[wid_end]])
                appeared++;
        }
        if(appeared == T.size()){
            while((appearCount[S[wid_start]]>expectCount[S[wid_start]]) || expectCount[S[wid_start]]==0)
            {
                appearCount[S[wid_start]]--;
                wid_start++;
            }
            if(minV > (wid_end-wid_start+1))
            {
                minV = wid_end-wid_start+1;
                min_start = wid_start;
            }
        }
    }
    if(minV == INT_MAX) return"";
    return S.substr(min_start,minV);
    }


Java实现如下

public String minWindow(String S, String T) {
        int win_start = 0;
        int win_realS = 0;
        int win_len = Integer.MAX_VALUE;
        int appeared = 0;
        HashMap<Character, Integer> expected = new HashMap<Character, Integer>();
        HashMap<Character, Integer> realAppeared = new HashMap<Character, Integer>();
        for(int i=0;i<T.length();i++){//store T char into map
        	int val = 1;
        	if(expected.containsKey(T.charAt(i))){
        		val = expected.get(T.charAt(i));
        		val++;
        	}
        	expected.put(T.charAt(i), val);
        }
        for(int i=0;i<S.length();i++){
        	if(expected.containsKey(S.charAt(i))){
        		int val = 0;
        		if(realAppeared.containsKey(S.charAt(i))){
        			val = realAppeared.get(S.charAt(i));
        			val++;
        		}else{
        			val = 1;
        		}
        		realAppeared.put(S.charAt(i), val);
        		if(val<=expected.get(S.charAt(i)))
        			appeared++;
        	}
        	if(appeared == T.length()){//have all the chars
        		while(!expected.containsKey(S.charAt(win_start))
        				|| (expected.containsKey(S.charAt(win_start)) && realAppeared.get(S.charAt(win_start))>expected.get(S.charAt(win_start)))){
        			if(!expected.containsKey(S.charAt(win_start)))
        				win_start++;
        			else{
        			int val = realAppeared.get(S.charAt(win_start));
        			val--;
        			realAppeared.put(S.charAt(win_start), val);
        			win_start++;
        			}
        		}        		
        		if(win_len>i-win_start+1){
        			win_len = i-win_start+1;
        			win_realS = win_start;
        		}
        	}
        }
        return (win_len == Integer.MAX_VALUE) ? "" : S.substring(win_realS, win_realS+win_len);
    }


9. Longest Substring Without Repeating Characters 

Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.

从左往右扫描,当遇到重复字母时,以上一个重复字母的index +1,作为新的搜索起始位置。比如


直到扫描到最后一个字母。
C++实现

int lengthOfLongestSubstring(string s) {
        int maxL=0;
        int len =0;
        int counts[26];
        memset(counts, -1, 26*sizeof(int));
    
        for(int i=0; i<s.size(); i++,len++){
            if(counts[s[i]-'a']>=0){
            maxL = max(maxL, len);
            len = 0;
            i = counts[s[i]-'a']+1;
            memset(counts,-1,26*sizeof(int));
        }
        counts[s[i]-'a'] = i;
    }
    return max(len, maxL);
    }


Java实现

public int lengthOfLongestSubstring(String s) {
        if(s.length() == 0) return 0;
		int start = 0;
		int end = 0;
		int maxLen = 0;
		HashMap<Character, Integer> charMap = new HashMap<Character,Integer>();
		while(end<s.length()){
			if(!charMap.containsKey(s.charAt(end))){
				charMap.put(s.charAt(end), end);
				int len = end-start+1;
				maxLen = Math.max(len, maxLen);
			}else{
				int val = charMap.get(s.charAt(end));
				for(int i=start;i<val+1;i++)
					charMap.remove(s.charAt(i));
				start = val+1;
				charMap.put(s.charAt(end), end);
			}
			end++;
		}
		return maxLen;
    }
v2

10 Interleaving String

Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2.

For example,
Given:
s1 = "aabcc",
s2 = "dbbca",

When s3 = "aadbbcbcac", return true.
When s3 = "aadbbbaccc", return false.

First we can consider this as a recursive problem.
If  s3[i1+i2+1] == s1[i1+1], search(i1+1,i2)
If  s3[i1+i2+1] == s2[i2+1], search(i1,i2+1)
until end. However, this can only pass the small test cases, but failed on the large test cases.

So we need to think of the dynamic programming (DP), which usually have much less complexity. In this problem, a 2D DP is more suitable.  As usual, the typical way of solving dp is to find the state, and the optimal function. Here, the state can be considered as: A[i][j], which means S3[i+j] can be formed by S1[i] and S2[j] (for simplicity here string starts from 1, in the code we need to deal with that string starts from 0).

So, we have the optimal function:
  A[i][j] =   (s3[i+j]==s1[i]  && match[i-1][j])  || (s3[i+j] ==s2[j] && match[i][j-1])

c++

<span style="font-family:Arial, Tahoma, Helvetica, FreeSans, sans-serif;font-size:12px;color:#444444;">bool isInterleave(string s1, string s2, string s3) {
         if(s1.size()+s2.size() != s3.size()) return false;
    bool **dp = new bool *[s1.size()+1];
    for(int i=0; i<s1.size()+1; i++){
        dp[i] = new bool [s2.size()+1];
    }
    dp[0][0] = true;
    for(int i=1; i<s1.size()+1; i++){
        if(s1[i-1]==s3[i-1] && dp[i-1][0])
            dp[i][0] = true;
    }
    for(int j=1; j<s2.size()+1; j++){
        if(s2[j-1]==s3[j-1] && dp[0][j-1])
            dp[0][j] = true;
    }
    for(int i=1; i<s1.size()+1; i++){
        for(int j=1; j<s2.size()+1; j++){
            if(s1[i-1]==s3[i+j-1] && dp[i-1][j])
                dp[i][j] = true;
            if(s2[j-1]==s3[i+j-1] && dp[i][j-1])
                dp[i][j] = true;
        }
    }
    return dp[s1.size()][s2.size()];
    }</span>
java

<span style="font-family:Arial, Tahoma, Helvetica, FreeSans, sans-serif;font-size:12px;color:#444444;">public boolean isInterleave(String s1, String s2, String s3) {
        int n1 = s1.length();
        int n2 = s2.length();
        if(n1+n2!=s3.length()) return false;
        boolean [][]flag = new boolean [n1+1][n2+1];
        for(int i=0;i<=n1;i++){
        	for(int j=0;j<=n2;j++){
        		flag[i][j] = false;
        	}
        }
        flag[0][0] = true;
        for(int i=1;i<=n1;i++){
        	if(s1.charAt(i-1)==s3.charAt(i-1)&& flag[i-1][0]) flag[i][0] = true;
        }
        for(int j=1;j<=n2;j++){
        	if(s2.charAt(j-1)==s3.charAt(j-1)&& flag[0][j-1]) flag[0][j] =true;
        }
        for(int i=1;i<=n1;i++){
        	for(int j=1;j<=n2;j++){
        		if((flag[i-1][j] && s1.charAt(i-1)==s3.charAt(i-1+j))||
        				(flag[i][j-1]&& s2.charAt(j-1)==s3.charAt(i+j-1))){
        			flag[i][j] = true;
        		}
        	}
        }
        return flag[n1][n2];
    }</span>




未完待续

Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.

For example,
"A man, a plan, a canal: Panama" is a palindrome.
"race a car" is not a palindrome.

Note:
Have you consider that the string might be empty? This is a good question to ask during an interview.

For the purpose of this problem, we define empty string as valid palindrome.

Analysis:

Use Two pointers, scan from end to start.

Java

public boolean isPalindrome(String s) {
        s = s.trim();
		if(s.length()<=0) return true;
		int start = 0;
		int end = s.length()-1;
		while(start<end){
			while(start<end && !(Character.isLetter(s.charAt(start))||Character.isDigit(s.charAt(start)))) start++;
			while(start<end &&  !(Character.isLetter(s.charAt(end))||Character.isDigit(s.charAt(end)))) end--;
			if(s.charAt(start)==s.charAt(end) || s.charAt(start)-'a'==s.charAt(end)-'A'||s.charAt(start)-'A' == s.charAt(end)-'a' ){
			start++;
			end--;
			}else {
				break;
			}
		}
		if(start>=end)
			return true;
		else {
			return false;
		}
    }

Another one:

public boolean isPalindrome(String s) {
        if(s.isEmpty()) return true;
        int len = s.length();
        int start = 0;
        int end = len-1;
        while(start<=end){
        	if(!isAlp(s.charAt(start))){
        		start++;
        		continue;
        	}
        	if(!isAlp(s.charAt(end))){
        		end--;
        		continue;
        	}
        	if(s.charAt(start)==s.charAt(end) || Math.abs(s.charAt(start)-s.charAt(end))==32){
        		start++;
				end--;
        	}else
        		return false;
        	
        }
        return true;
    }
	public boolean isAlp(char c){
		if((c<='z'&&c>='a')||(c<='Z'&&c>='A')|| (c>='0'&&c<='9'))
			return true;
		else
			return false;
	}


c++

bool isPalindrome(string s) {
      if(s.empty()) return true;
    int len = s.length();
    int r = len-1;
    int l = 0;
    while(l<=r){
        if((s[l] >= 'a' && s[l]<='z') || (s[l]>='A' && s[l]<='Z')||(s[l])>='0'&& s[l]<='9'){
            if((s[r] >= 'a' && s[r]<='z') || (s[r]>='A' && s[r]<='Z')||(s[r]>='0' && s[r]<='9')){
                if(s[l] == s[r] || s[l]-'a'==s[r]-'A' || s[l]-'A' == s[r]-'a'){
                    l++;
                    r--;
                }
                else
                    return false;
            }else{
                r--;
                continue;
            }
        }

        else{
            l++;
            continue;
        }
    }
    return true;
    }





基于Super-Jacoco的精准测试实践之路 灵魂拷问这个版本的影响范围到底有多大?研发改动了代码,为什么不通知测试?测试用例真的全面覆盖了吗?测试同学的测试覆盖情况该怎么评估?什么是精准测试概念借助技术手段、通过辅助算法对软件测试过... 阅读详情

相关推荐

AD20/Altium designer——元器件批量命名与编号的高效技巧

本文详细介绍了在AD20/Altium Designer中实现元器件批量命名与编号的高效技巧。通过解析核心的“原理图标注”功能,从基础全局操作到进阶的按模块分区、利用标识符及合并BOM等智能方法,帮助硬件工程师彻底告别手动编号,大幅提升设计效率与文档规范性,并融入了一套完整的实战工作流。

whisky的博客 568

String Typing(字符串操作)

You are given a string s consisting of n lowercase Latin letters. You have to type this string using your keyboard. Initially, you have an empty string. Until you type the whole string, you may perfo...

好吗好的~的技术博客 2245

手把手教你用BQ Studio给BQ40Z50电量计“做体检”:从Golden Learning到精度验证的全流程实操

本文详细介绍了如何使用BQ Studio对BQ40Z50电量计进行全流程调试,从Golden Learning到精度验证。通过硬件连接、参数配置和优化技巧,帮助工程师提升电池管理系统的精度和性能,适用于BMS开发和电量计校准的实际应用场景。

weixin_30824599的博客 450

5. Java- 最长公共前缀

package com.dhl.beyond; /** * 编写一个函数来查找字符串数组中的最长公共前缀。 * * 如果不存在公共前缀,返回空字符串 ""。 */ public class 最长公共前缀 { public static void main(String[] args) { String[] str = {"aafdsfs","aafdsfs"}; System.out.println(longestCommonPrefix(str));

Beyond_Nothing 1081

6种常用数据分析方法详解:从描述统计到时间序列

数据分析是连接数据与业务决策的桥梁。面对海量数据,掌握描述性统计与对比分析可快速了解现状与差距;相关分析与回归分析能揭示变量间的关联与影响大小;聚类分析用于用户分群,时间序列分析则预测未来走势。这些方法广泛应用于用户画像、销量预测、活动效果评估等场景,是数据分析师和运营人员必备的技能。系统掌握这6种核心方法的使用场景、原理逻辑与实操步骤,能够帮助读者建立完整分析框架,真正用数据驱动业务增长。

weixin_34405354的博客 335

Android自动化新方案:ESP32-C3蓝牙HID模拟触控与手势操作实战(附源码)

本文详细介绍了使用ESP32-C3通过蓝牙HID协议实现Android设备自动化操作的完整方案。该硬件方案成本低廉且能完美规避系统风控,可模拟鼠标移动、点击及复杂手势操作,延迟低于50毫秒,适用于游戏连招和应用测试等场景。文章包含完整的源码实现和性能优化技巧。

kotlin6android的博客 377

strlen, strcpy, strcmp函数的实现

在Bjarne Stroustrup(C++创始人,他的主页)所写的《The C++ Programming Language, special edition》书中的第6章6.6节的第10题练习题中,要求实现strlen, strcpy, strcmp三个函数,2011年11月份我已发过两篇文章来实现此三个函数(字符串处理函数的实现,strcmp函数的实现),以前的实现代码中,为了避免命名冲突,

MJN 3203

单细胞分析(19)—— 单细胞转录组基因集评分方法

在单细胞RNA测序(scRNA-seq)分析中,基因集评分(Gene Set Scoring)是一项关键任务,能帮助研究者识别细胞功能状态

阅读文献,记录学习笔记 2439

Python程序输入一个字符串并查找总数的大写和小写字母

Given a string str1 and we have to count the total numbers of uppercase and lowercase letters. 给定字符串str1 ,我们必须计算大写和小写字母的总数。 Example: 例: Input: "Hello World!" Output: Uppercase ...

cumudi0723的博客 1万+

从 CDS 接口到 ABAP 运行时,深入理解 SAP RAP Custom Entity

CDS Custom Entity 是一种非 SQL、瞬态的 CDS 实体,不依赖 HANA SQL 读取数据,而是通过 ABAP 类实现查询逻辑(如 RFC、OData、BAPI 等)。它在 CDS 层定义数据契约(字段、键、关联、注解),由 @ObjectModel.query.implementedBy 指向实现 IF_RAP_QUERY_PROVIDER~SELECT 的类,真正执行数据获取。适用于无法用 SQL 表达的数据源,如远程系统或 API。其核心是“接口 + 实现”模式,运行时由 RAP

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 170

基于强化学习的多无人机路径规划

我们使用了Dueling Double Deep Q-Network(DDDQN)算法来训练智能体,这个算法在深度Q学习算法的基础上进行了升级,具有更快的收敛速度和更好的性能。本文提出了一种基于强化学习的算法,实现了多无人机路径规划,并提供相应的MATLAB代码。通过基于强化学习的多无人机路径规划算法,我们能够高效地解决复杂环境下的任务需求,并在实际应用中取得了良好的效果。首先,我们定义了状态空间和动作空间。实验结果表明,我们的方法能够有效地解决多无人机路径规划问题,提高了任务完成的效率和准确率。

DjjPython的博客 820

语法练习:front_times

Given a string and a non-negative int n, we’ll say that the front of the string is the first 3 chars, or whatever is there if the string is less than length 3. Return n copies of the front;front_times(‘Chocolate’, 2) → ‘ChoCho’ front_times(‘Chocolate’, 3)

sunbocong的博客 406

基于MATLAB的脑功能网络工具箱:BCT与FCLab

脑功能网络分析是神经科学领域的一个重要研究方向,它通过分析大脑中神经元之间的连接模式和信息传递方式,揭示脑网络的结构和功能。在这个领域,MATLAB是一个广泛使用的工具,提供了丰富的函数和工具箱来进行脑功能网络的分析和可视化。这些工具箱提供了丰富的函数和工具,使得脑功能网络的计算和分析变得更加简单和高效。在上述示例代码中,我们首先导入BCT工具箱,并构建一个邻接矩阵来表示脑网络的连接关系。在上述示例代码中,我们首先导入FCLab工具箱,并导入脑功能数据。函数对数据进行预处理,如去除噪声、降采样等操作。

web_bug407的博客 2611

【LeetCode Cookbook(C++ 描述)】一刷字符串(String)

本系列文章仅是 GitHub 大神 @halfrost 的刷题笔记《LeetCode Cookbook》的提纲以及示例、题集的 C++转化。原书请自行下载学习。本篇文章涉及新手应该优先刷的几道经典字符串算法题,以后会更新“二刷”“三刷”等等。

David Max 的博客 780

Camera2Demo

在Camera2 的基础上进行封装,使得Camera2一堆初始化逻辑与Activity分离,降低耦合度,完成预览拍照并保存的操作

蓝牙模块HM-10手册

蓝牙模块HM-10手册,该手册对蓝牙模块HM-10进行了详细的介绍和使用方法以及一些AT指令。

Task4:LeetCode1:twoSum; LeetCode344:Reverse String;LeetCode151:Reverse Words in a String

1.Two Sum(两个数求和) class Solution: def twoSum(self, nums: 'List[int]', target: int) -> 'List[int]': dicti = {} for i, n in enumerate(nums): if n in dicti: ...

m0_37548423的博客 168

复分析 阿尔福斯(Ahlfors) 第三版答案 英文

答案分为十章,有部分习题没有答案,全英文复分析阿尔福斯(Ahlfors) 第三版答案

Reverse Words in a String -- LeetCode

原题链接: http://oj.leetcode.com/problems/reverse-words-in-a-string/  这道题是字符串处理的题目,我们先介绍一种很直接的做法,就是类似于java中String::split函数做的操作,把字符串按空格分开,不过我们把重复的空格直接忽略过去。接下来就是把得到的结果单词反转过来得到结果。因为过程中就是一次扫描得到字符串,然后再一次扫描得出结

Code Ganker 7804

锂电池充电器电路设计 里面有电路

锂电池充电器电路设计 里面有电路 3.7V升压到5V电路设计。

每日一恋 - LeetCode 438. Find All Anagrams in a String(找到字符串中所有字母异位词)

Given a string s and a non-empty string p, find all the start indices of p’s anagrams in s. Strings consists of lowercase English letters only and the length of both strings s and p will not be large...

love4rui的博客 591

LeetCode394 字符串解码

LeetCode394. 字符串解码

weixin_45771864的博客 567

单词压缩编码问题(LeetCode)的笨方法以及由此产生的String类型陷阱再复习

首先,题目是这样的: 给定一个单词列表,我们将这个列表编码成一个索引字符串 S 与一个索引列表 A。 例如,如果这个列表是 [“time”, “me”, “bell”],我们就可以将其表示为 S = “time#bell#” 和 indexes = [0, 2, 5]。 对于每一个索引,我们可以通过从字符串 S 中索引的位置开始读取字符串,直到 “#” 结束,来恢复我们之前的单词列表。 那么成功对...

LifeGoesOn 403

【力扣刷题】205.同构字符串(哈希表)

给定两个字符串s和t,判断它们是否是同构的。 如果s中的字符可以按某种映射关系替换得到t,那么这两个字符串是同构的。 每个出现的字符都应当映射到另一个字符,同时不改变字符的顺序。不同字符不能映射到同一个字符上,相同字符只能映射到同一个字符上,字符可以映射到自己本身。

m0_67763367的博客 563

刷题——字符串中的单词数(力扣)

字符串的单词数——力扣

L326214的博客 560

中国铁路网矢量shp数据获取与处理实战:从坐标系到缓冲区分析

在GIS工程中,矢量数据是空间分析的基石,而铁路网作为线性要素,其shp数据的质量直接决定项目成败。Shapefile由几何、索引与属性表等多个文件构成,坐标系(WGS84、CGCS2000、GCJ02)的混乱是数据不可用的头号原因。通过OpenStreetMap与国家基础地理信息中心等正规渠道获取的铁路网数据,经投影转换、拓扑修复与属性清洗后,可用于缓冲区分析、物流选址及人口覆盖评估。本文结合真实项目经验,详解从数据获取、QGIS/ArcGIS预处理到多源数据融合的完整链路,帮助读者避开坐标系错乱、属性乱

weixin_34129696的博客 338

力扣 hot100 Day2

同样是直接计数,不过处理的比第一种要灵活,通过string存放各个字母的数量的ASCII码,即使为多位数,仍不需要特殊处理,因为本质不是数字,而是char字符。利用质数相乘的唯一性,实现给各个字母分配权重。不过cpp提交超出了longlong的范围,测试用例比较夸张。通过对大质数取模处理,跑成功了,不过这样应该存在风险,不能保证百分比准确。无脑思路,通过string数组存储每个字符串的字母分布情况,结合哈希表进行分类存储,最后输出,最终效率感人。是由重新排列源单词的所有字母得到的一个新单词。

qq_51397044的博客 195

LeetCode【#9】Palindrome Number 【string的使用】

题目链接: 点击跳转 题目: Determine whether an integer is a palindrome. An integerisapalindrome when itreads the same backward as forward. Example 1: Input: 121 Output: true Example 2: Input: -...

Mikchy的博客 215

Leetcode——151.反转字符串中的单词

对字符串还是不够熟练,有好多方法在用的时候想不起来用到很多String的内置函数,非常简洁。最后这种题解,只需新建一个新的StringBuilder类型对象,然后在该StringBuilder进行修改,不需要额外开辟数组或集合,空间复杂度低。就是太复杂了!!学习过后复现都很难!!!

2201_75433472的博客 484

小练习 - LeetCode151 Reverse Words in a String的C语言解法

LeetCode 151. Reverse Words in a String 很适合练习C语言基础,练习一个OJ题目除了找最佳解法,还可以多想想刻意去练习一些数据结构等其他知识点,让练习举一反三。 Given an input string, reverse the string word by word. Example: Input: “the sky is blue”, Output: ...

Life runs on code 673
上一篇: LeetCode 之水箱问题
下一篇: LeetCode 之模拟&贪心
Mavs
博客等级 码龄17年 166粉丝 296原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值