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;
    }





AI Agent Harness与SCADA系统集成 简单来说,AI Agent Harness是Industrial AI Agent的“中央调度室+装备库+知识库+安全网”把不同技术栈、不同部署环境(云/边/端)、不同功能(感知、推理、决策、执行、验证)的“零散Agent”组装成具备特定工业场景能力的Agent Team(如聚合反应根因诊断Agent Team);管理Agent Team的生命周期(创建、初始化、调度、监控、销毁);提供统一的工业多工具调用接口(对接SCADA、MES、PLC、DCS、巡检机器人、数字孪生平台等);内置。 阅读详情

相关推荐

Vc出现不能连接到一个或多个 vCenter server 系统:http://vcenter-vx.utibet.edu.cn:443/sdk

问题描述: 解决办法: esxi6.7的bug 第一种通过升级系统来解决问题 第二种是通过删除数据来解决 第一步:进入到esxi的shell 第二步查看其中的服务开启状态 第二步 df -h 第三步 /opt/vmware/vpostgres/current/bin/psql -d VCDB -U postgres 第四步 SELECT nspname || '.' || relname AS "relation", pg_size_pretty(pg_total_relation_size(C.oi

m0_49328536的博客 9900

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

IsaacLab 从入门到精通(一) 环境配置和依赖安装

本系列文章将针对机器人操作任务中的强化学习平台IsaacLab提供较为全面的教程

DejaWu33的博客 1万+

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

银河麒麟桌面版V10搭建Qt4.8.6开发环境

银河麒麟桌面版V10搭建Qt4.8.6开发环境

qq_34932364的博客 2399

XGBoost特征重要性为0的问题:深度解析与应对策略

在机器学习领域,XGBoost(Extreme Gradient Boosting)作为一款高效且强大的集成学习算法,已经被广泛应用于各类预测任务中。然而,在实际应用过程中,许多数据科学家和工程师们遇到了一个令人困惑的现象——某些特征的重要性值为0。这不仅影响了模型的解释性,还可能导致特征选择过程中的误判。本文将深入探讨这一问题,分析其背后的原因,并提供相应的解决方案。在深入探讨特征重要性为0的问题之前,我们首先需要了解XGBoost是如何计算特征重要性的。XGBoost提供了三种常见的特征重要性计算方法:

cda2024的博客 1705

strlen, strcpy, strcmp函数的实现

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

MJN 3203

Android 11.0 app添加校验锁(输入密码才能进入app)

11.0定制化开发中客户要求给app添加锁,就是点击app 图标时,会弹出Dialog,需要输入密码才能进入app中,就是应用校验锁, 最开始想到在Launcher3中实现,但是如果更换了默认Launcher 又不行了 所以最终还是得拦截app启动Activity 从这里入手了 Launcher与APP是在两个不同的进程中,他们之间的通信是通过Binder完成的,点击Launcher上的某个APP,这时会调用Launcher的startActivitySafely方法。 public boolean sta

安卓兼职framework和app工程师的博客 1952

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万+

CANoe.DiVa的应用——生成测试用例过程流程详解(一)

Diva 生成用例过程

LOVE135149的博客 7926

Android Jetpack 最全面试题及参考答案

要使用 WorkManager 定义一个异步任务,以下是详细步骤。首先,需要创建一个继承自 Worker 类的自定义类,这个类代表了要执行的具体任务逻辑。// 在这里编写具体的任务逻辑,比如从网络下载文件try {在上述代码中,doWork方法就是任务的核心执行逻辑所在,这里模拟了从给定的 URL 下载文件到本地的操作,若下载成功返回,若出现异常则返回。然后,在需要调度任务的地方,比如在某个 Activity 或者 Fragment 中,通过构建 WorkRequest 来安排任务执行。

大模型大数据攻城狮的专栏 1895

语法练习: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

【Dify】PPT生成工具应用

本文介绍了一款自动化PPT生成工具,通过智能接口将文本内容高效转化为结构化演示文档。该系统采用三阶段工作流(内容输入、HTTP请求上传、文件输出),无需复杂操作即可生成专业PPT。工具适用于教学课件、产品发布、企业培训等场景,能显著提升内容表达效率,特别适合初学者快速制作演示材料。文章详细说明了核心节点、应用场景及开发资源,为文本到PPT的自动化转换提供了实用解决方案。

Mr数据杨 1216

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

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

David Max 的博客 780

efm32 入门.pdf

本PDF共计22页,介绍的是操作驱动API,下载与否自己斟酌。

STM32F407中文手册

STM32f407中文手册 本参考手册面向应用开发人员,提供有关使用 STM32F405xx/07xx、STM32F415xx/17xx、 STM32F42xxx 和 STM32F43xxx 微控制器存储器与外设的完整信息。STM32F405xx/07xx、STM32F415xx/17xx、STM32F42xxx 和 STM32F43xxx 构成一个微 控制器系列,各产品具有不同的存储器大小、封装和外设。有关订购信息以及器件的机械与电气特性,请参见数据手册。有关 ARM Cortex™-M4F 内核的信息,请参见《Cortex™-M4F 技术参考手册》。

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

文档:亲测可用解决vnc灰屏,黑屏,鼠标大黑叉情况

主要解决vnc-viewer灰屏,黑屏,鼠标大黑叉等现象,详细见文档。

Reverse Words in a String -- LeetCode

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

Code Ganker 7804

VC中sqlite的使用

在VC中对sqlite的使用,实现数据库大批数据的快速插入,读取数据库中的数据在ListCtrl中显示

每日一恋 - 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、付费专栏及课程。

余额充值