在Unix系统中,查找两个字符串的最长公共子串的shell命令是什么? 例如:foo 'abcdefghi' 'abjklmdefnop' 输出结果为:def
在Unix系统中,查找两个字符串的最长公共子串的shell命令是什么? 例如:foo 'abcdefghi' 'abjklmdefnop' 输出结果为:def
#!/bin/bash
word1="$1"
word2="$2"
if [ ${#word1} -lt ${#word2} ]
then
word1="$2"
word2="$1"
fi
for ((i=${#word2}; i>0; i--)); do
for ((j=0; j<=${#word2}-i; j++)); do
if [[ $word1 =~ ${word2:j:i} ]]
then
echo ${word2:j:i}
exit
fi
done
done
将上面的内容保存为文件substr.sh 然后执行chmod +x substr.sh
pranithk @ ~
09:24:32 :) $ ./substr.sh 'abcdefghi' 'abcdeghi'
abcde
pranithk @ ~
09:24:33 :) $ ./substr.sh 'abcdefghi' 'abjklmdefnop'
def