算法:字符串處理

算法:字符串處理

字符串的排列

問題描述

  輸入一個字符串,打印出該字符串中字符的全部排列。例如,輸入字符串abc,則打印出由字符a、b、c所能排列出來的全部字符串abc,acb,bac,bca,cab,cba.java

解決思路

  咱們求整個字符串的排列,能夠分紅兩步,第一步求全部可能出如今第一個位置的字符,即把第一個字符與後面全部字符交換。ios

  

  第二步,固定第一個字符,求後面全部字符的排列。這時仍把後面的字符分紅兩部分:後面的第一個字符,以及這個字符以後的全部字符。而後把第一個字符逐一和後面的字符交換。算法

Java實現代碼

  private static HashSet<String> resultSet = new HashSet<>();
  public static void main(String[] args) {
        String test = "abcd";

        printStr(test,0);
        Iterator<String> it = resultSet.iterator();
        while (it.hasNext())
            System.out.println(it.next());
    }

    public static void printStr(String test,Integer ptr)
    {
        if(ptr<=test.length())
        {
            char[] chars = test.toCharArray();
            for(int i=ptr;i<chars.length;i++)
            {

                char temp = chars[i];
                chars[i]=chars[ptr];
                chars[ptr]=temp;
                resultSet.add(new String(chars));
                printStr(new String(chars),ptr+1);
            }
        }
    }

最長不含重複字符的子字符串

問題描述

  請從字符串中找出一個最長的不包含重複字符的子字符串,計算該最長子字符串的長度。假設字符串中只還有'a'~'z'的字符。spa

解決思路

Java實現代碼

構造迴文串

問題描述

  給定一個字符串s,你能夠從中刪除一些字符,使得剩下的串是一個迴文串。如何刪除才能使得迴文串最長呢?
輸出須要刪除的字符個數。blog

解決思路

提到迴文串,天然要利用迴文串的特色,想到將源字符串逆轉後,「迴文串」(不必定連續)至關於順序沒變
求原字符串和其反串的最大公共子序列(不是子串,由於能夠不連續)的長度(使用動態規劃很容易求得),而後用原字符串的長度減去這個最大公共子串的長度就獲得了最小編輯長度圖片

最大公共子序列ci

   最長公共子序列的結構有以下表示:
   設序列X=<x1, x2,="" …,="" xm="">和Y=<y1, y2,="" …,="" yn="">的一個最長公共子序列Z=<z1, z2,="" …,="" zk="">,則:
   1> 若 xm=yn,則 zk=xm=yn,且Zk-1是Xm-1和Yn-1的最長公共子序列; 
   2> 若 xm≠yn且 zk≠xm ,則 Z是 Xm-1和 Y的最長公共子序列;
   3> 若 xm≠yn且 zk≠yn ,則 Z是 X和 Yn-1的最長公共子序列;
   其中Xm-1=<x1, x2,="" …,="" xm-1="">,Yn-1=<y1, y2,="" …,="" yn-1="">,Zk-1=<z1, z2,="" …,="" zk-1="">。

<x1, x2,="" …,="" xm-1=""><y1, y2,="" …,="" yn-1=""><z1, z2,="" …,="" zk-1=""> 字符串

圖片演示字符串處理

 

C++實現最大公共子序列

#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
const int MAX = 1001;
int MaxLen[MAX][MAX]; //最長公共子序列,動態規劃求法
int maxLen(string s1, string s2){
    int length1 = s1.size();
    int length2 = s2.size();
    for (int i = 0; i < length1; ++i)
        MaxLen[i][0] = 0;
    for (int i = 0; i < length2; ++i)
        MaxLen[0][i] = 0;
     
    for (int i = 1; i <= length1; ++i)
    {
        for (int j = 1; j <= length2; ++j)
        {
            if (s1[i-1] == s2[j-1]){
                MaxLen[i][j] = MaxLen[i-1][j - 1] + 1;
            }
            else
            {
                MaxLen[i][j] = max(MaxLen[i - 1][j], MaxLen[i][j - 1]);
            }
        }
    }
 
    return MaxLen[length1][length2];
}
 
int main(){
    string s;
    while (cin >> s){
        int length = s.size();
        if (length == 1){
            cout << 1 << endl;
            continue;
        }
        //利用迴文串的特色
        string s2 = s;
        reverse(s2.begin(),s2.end());
        int max_length = maxLen(s, s2);
        cout << length - max_length << endl;
    }
    return 0;
}
相關文章
相關標籤/搜索